Depth-First Search (DFS)
is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It can be implemented using recursion or an explicit stack.
Let's consider a simple graph:
A
/ \
B
C
/ \ \
D
E
F
const graph = {
A: ["B", "C"],
B: ["A", "D", "E"],
C: ["A", "F"],
D: ["B"],
E: ["B"],
F: ["C"]
};
Output:
A B D E C F
O(V + E)
where V
is the number of vertices and E is the number of edges.
O(V)
for storing visited nodes in recursion.
https://drawtocode.vercel.app/problems/depth-first-search
Loading component...
Loading component...
INPUT : graph = { A: ["B", "C"], B: ["A", "D", "E"], C: ["A", "F"], D: ["B"], E: ["B"], F: ["C"] }
OUTPUT: A B D E C F
public static void main(String[] args) {
Map<Character, List<Character>> graph = new HashMap<>();
graph.put('A', Arrays.asList('B', 'C'));
graph.put('B', Arrays.asList('A', 'D', 'E'));
graph.put('C', Arrays.asList('A', 'F'));
graph.put('D', Arrays.asList('B'));
graph.put('E', Arrays.asList('B'));
graph.put('F', Arrays.asList('C'));
Set<Character> visited = new HashSet<>();
dfs(graph, 'A', visited);
}//function end
static void dfs(Map<Character, List<Character>> graph, char node, Set<Character> visited) {
if (visited.contains(node)) {
return;
}
System.out.print(node + " ");
visited.add(node);
for (char neighbor : graph.getOrDefault(node, new ArrayList<>())) {
dfs(graph, neighbor, visited);
} //Loop End
}//function End
Utility Function is not required.