This is where I keep all my notes
01-BFS
by srabon
Consider how to solve the following problem:
You are given a directed graph in which every edge has a weight 0 or 1. Find the shortest distance from the Vertex S to each vertex on this graph.
Solution
This problem can be solved with algorithms of solving shortest path problems like Dijkstra's algorithm. But 01-BFS is more efficient.
- Prepare an empty deque.
- Define provisional shortest distances
D[vertex index] = { provisional distance }as follows,D[S] = 0D[x] = infinityfor every vertexxother thanS.
- Add vertex
Sas the only element of the deque. - Repeat the following until deque becomes empty,
- Pop on element from the head of the deque. Let
Vbe the popped vertex. - If
Vhas not been visited yet, do the following operation and markVas visited,- For each vertex
Wadjacent toV, do the following,- If the length of the edge connecting
VandWis0andD[W] > D[V], then pushWto the head of the deque and letD[W] = D[V]. - If the length of the edge connecting
VandWis 1 andD[W] > D[V] + 1, then pushWto the tail of the deque and letD[W] = D[V] + 1
- If the length of the edge connecting
- For each vertex
- Pop on element from the head of the deque. Let
While the outline of the algorithm is the same as Dijkstra's algorithm, it is distinctive in the usage of the deque. In this algorithm, the deque plays the role of priority queue in Dijkstra's algorithm.
Select a Category:
Programming