对最近学习的基础算法做一些总结,并举出一些相应的例子,仅此作为记录。
(未完待续…)
图的遍历(Graph Traversal)
DFS:
function DFS(hV, Ei)
mark each node in V with 0
count ← 0
for each v in V do
if v is marked 0 then
DfsExplore(v )
function DfsExplore(v )
count ← count + 1
mark v with count
for each edge (v , w) do ⊲ w is v ’s neighbour
if w is marked with 0 then
DfsExplore(w)
BFS:
function BFS(hV, Ei)
mark each node in V with 0
count ← 0, init(queue) ⊲ create an empty queue
for each v in V do
if v is marked 0 then
count ← count + 1
mark v with count
inject(queue, v ) ⊲ queue containing just v
while queue is non-empty do
u ← eject(queue) ⊲ dequeues u
for each edge (u, w) adjacent to u do
if w is marked with 0 then
count ← count + 1
mark w with count
inject(queue, w) ⊲ enqueues w
Topological Sorting:
最短路径
DP
核心思想:选取中间点
Warshall
for k ← 1 to n do
for i ← 1 to n do
if A[i, k] then
for j ← 1 to n do
if A[k, j] then
A[i, j] ← 1
Floyd
基本思想:
(1) 最开始只允许经过1号顶点进行中转;
(2) 接下来只允许经过1和2号顶点进行中转,以此类推;
(3) 直到最后允许经过1~n号所有顶点进行中转,求任意两点之间的最短路程。
function Floyd(W [1..n, 1..n])
D ← W
for k ← 1 to n do
for i ← 1 to n do
for j ← 1 to n do
D[i, j] ← min(D[i, j], D[i, k] + D[k, j])
return D
greedy
核心思想:选取目前最短的路径
Prim
最小生成树(minimum spanning tree)
function Prim(hV, Ei)
for each v ∈ V do
cost[v ] ← ∞
prev [v ] ← nil
pick initial node v0
cost[v0] ← 0
Q ← InitPriorityQueue(V) //全结点入队
while Q is non-empty do
u ← EjectMin(Q)//逐个出队
for each (u, w) ∈ E do
if weight(u, w) < cost[w] then
cost[w] ← weight(u, w)
prev [w] ← u
Update(Q, w, cost[w])
Dijkstra
function Dijkstra(hV, Ei, v0)
for each v ∈ V do
dist[v ] ← ∞
prev [v ] ← nil
dist[v0] ← 0
Q ← InitPriorityQueue(V)//全结点入队
while Q is non-empty do
u ← EjectMin(Q)//逐个出队
for each (u, w) ∈ E do
if dist[u] + weight(u, w) < dist[w] then
dist[w] ← dist[u] + weight(u, w)
prev [w] ← u
Update(Q, w, dist[w])