For some reason I never really implemented DFS and BFS before. Time has come. Ideas are simple:
-
DFS: Go down to the neighbours and mark vertices on the way until can’t; then go one step back and proceed with the rest of the neighbours.
-
BFS: Put all the neighbours into the queue; poll (pop and remove) from the queue and put all its neighbours into the queue; repeat.
Let’s do it in Java, since it’s the most common interview language. First let’s define a simple graph on integers as a adjacency list:
1
static HashMap<Integer, ArrayList<Integer>> graph = new HashMap<Integer, ArrayList<Integer>>();
Let’s read the graph from the following txt file:
1
2
3
4
5
6
7
8
0 1
1 0 2
2 1 3 4
3 2 5
4 2 6
5 3 6 7
6 4 5
7 5
Now DFS:
1
2
3
4
5
6
7
8
9
10
static void dfs(int v){
visited[v] = true;
System.out.print("Visiting " + String.valueOf(v) + ": ");
printBoolArray();
for (int u : graph.get(v)){
if (!visited[u]){
dfs(u);
}
}
}
And BFS:
1
2
3
4
5
6
7
8
9
10
11
12
13
static void bfs(int v){
visited[v] = true;
System.out.print("Visiting " + String.valueOf(v) + ": ");
printBoolArray();
for (int u : graph.get(v)){
if (!visited[u] && !queue.contains(u)){
queue.add(u);
}
}
if (!queue.isEmpty()){
bfs(queue.poll());
}
}
So BFS a little bit more straight forward, while for BFS we need to create queue and do extra check. Both algorithms are O(E) time complexity.