Unweighted Graphs: Breadth-First Search
Learn about the breadth-first search algorithm and its applications in solving the shortest paths problem in unweighted graphs.
Implementation of breadth-first search
In the simplest special case of the shortest path problem, all edges have weight 1, and the length of a path is just the number of edges. This special case can be solved by a species of our generic graph-traversal algorithm called breadth-first search. Breadth-first search is often attributed to Edward Moore, who described it in 1957 (as “Algorithm A”) as the first published method to find the shortest path through a maze. Especially in the context of VLSI wiring and robot path planning, breadth-first search is sometimes attributed to Chin Yang Lee, who described several applications of Moore’s “Algorithm A” (with proper credit to Moore) in 1961. However, in 1945, more than a decade before Moore considered mazes, Konrad Zuse described an implementation of breadth-first search as a method to count and label the components of a disconnected graph.
Breadth-first search maintains a first-in-first-out queue of vertices, which initially contains only the source vertex . At each iteration, the algorithm pulls a vertex from the front of the queue and examines each of its outgoing edges . Whenever the algorithm discovers an outgoing tense edge , it relaxes that edge and pushes vertex onto the queue. The algorithm ends when the queue becomes empty.
Algorithm
Implementation
import java.util.*;@SuppressWarnings("unchecked")public class Main {private static final int INF = 1000000000;private static final int MAXN = 100005;private static ArrayList<Integer>[] adj = new ArrayList[MAXN];private static int[] dist = new int[MAXN];private static int[] pred = new int[MAXN];private static boolean[] visited = new boolean[MAXN];private static void InitSSSP(int s) {for (int i = 0; i < MAXN; i++) {dist[i] = INF;pred[i] = -1;visited[i] = false;}dist[s] = 0;visited[s] = true; // initialize starting node as visited}private static void Push(int s, Queue<Integer> q) {q.add(s);visited[s] = true;}private static void bfs(int s) {InitSSSP(s);Queue<Integer> q = new LinkedList<>();Push(s, q);while (!q.isEmpty()) {int u = q.remove();for (int v : adj[u]) {if (dist[v] > dist[u] + 1) {// u->v is tensedist[v] = dist[u] + 1;pred[v] = u; // relax u->vif (!visited[v]) {// add v to queuePush(v, q);}}}}}public static void main(String[] args) {// example usagefor (int i = 0; i < MAXN; i++) {adj[i] = new ArrayList<>();}adj[1].add(2);adj[1].add(3);adj[2].add(4);adj[3].add(4);bfs(1);for (int i = 1; i <= 4; i++) {System.out.println("Shortest distance from 1 to " + i + ": " + dist[i]);}}}
Explanation
- Line 2: The command
@SuppressWarnings("unchecked")
removes any unwanted warning that may appear during the compilation of the code. - Line 5: This line declares a constant variable named
INF
and initializes it with the value1000000000
. - Lines 23–26: In Dijkstra’s algorithm, when a vertex is visited for the first time, its neighbors can be added to the priority queue (in the order of increasing distance from the source vertex) for further processing. The
Push
function performs this task by adding a vertexs
to the end of the queueq
and setting its visited flag totrue
. - Lines 53–57: Add edges to the graph and then call the
BFS
algorithm with the starting node1
.
Modifications of breadth-first search
Breadth-first search is somewhat easier to analyze if we break its execution into phases, by introducing an imaginary token. Before we pull any vertices, we push the token into the queue. The current phase ends when we pull the token out of the queue; we begin the next phase when we push the token into the queue again. Thus, the first phase consists entirely of scanning the source vertex . The algorithm ends when the queue contains only the token. The modified algorithm is shown below, and the illustration shows an example of this algorithm in action. Let us emphasize that these modifications are merely a convenience for analysis; with or without the token, the algorithm es and ...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy