DFS or breadth first search is one of the most commonly used algorithms to search for an item in non-linear data strcutures like trees and graphs.
Depth First Search (DFS) is similar to Breadth-First Search (BFS) with the difference in terms of how intermediate elements are held before processing.
While BFS will always process nodes in the order those are found (FIFO), DFS, on the other hand, will process nodes in the reverse order of their discovery (LIFO), i.e., DFS processes the record that is most recently discovered before processing records that were found before.
Consider the same illustration that we used for BFS:
Assuming the start node to be the one with value 1, the nodes that the algorithm will next traverse will be 4 and 5 before traversing 2 (or 2 and 3 before traversing 4).
Like BFS, we use an additional data structure (Stack) to temporarily hold intermediate nodes to block their processing until all the nodes in the current hierarchy are processed. As we know, stack provides LIFO traversal of its elements; it helps us to process the graph elements along the hierarchy instead of their level.
On a high level, the algorithm looks like the following:
S
with the start node.V
as a boolean array of size equal to the number of vertices.S
is not empty, pop its head element
.element
is equal to the key
we are looking for.element
as visited in the V
array.adj
of element:
adj
is not visited already in the V, and is not discovered in S
, push it to S
.Let’s try this algorithm for the given input for key 3:
In the next step, when we pop 3
from the top of the discovered stack, it will pass the comparison test and is returned to denote the presence.
public int search(int[][] graph, int start, int key){
boolean[] visited = new boolean[graph.length];
Stack<Integer> discovered = new Stack<>();
discovered.add(start);
while(!discovered.isEmpty()){
Integer visitedNode = discovered.pop();
if(visitedNode == key){
return visitedNode;
}
visited[visitedNode] = true;
// for each neighbor, check if the two vertices are connected
// if yes, and the neighbor is not visited already
// add it to the discovered list
for(int neighbor = 0; neighbor < graph.length; neighbor++){
// graph[visitedNode][neighbor] != 0 is neighbor check
// !visited[neighbor] - is not be visited already
// !discovered.contains(neighbor) - is not discovered already via some other node
if(graph[visitedNode][neighbor] != 0 && !visited[neighbor] && !discovered.contains(neighbor)){
discovered.push(neighbor);
}
}
}
return -1;
}
Similar to BFS, the overall complexity of this algorithm is dependent on the underlying data structure used to represent the graph:
Be notified of new posts. Subscribe to the RSS feed.