AlgoMaster Logo

Depth First Search (Iterative)

graph=[[1,2],[3,4],[5],[5],[5],[]],startNode=0
1public List<Integer> depthFirstSearch(int[][] graph, int start) {
2    int n = graph.length;
3    boolean[] visited = new boolean[n];
4    Stack<Integer> stack = new Stack<>();
5    List<Integer> result = new ArrayList<>();
6
7    stack.push(start);
8
9    while (!stack.isEmpty()) {
10        int current = stack.pop();
11
12        if (visited[current]) {
13            continue;
14        }
15
16        visited[current] = true;
17        result.add(current);
18
19        // Add neighbors in reverse order
20        for (int i = graph[current].length - 1; i >= 0; i--) {
21            int neighbor = graph[current][i];
22            if (!visited[neighbor]) {
23                stack.push(neighbor);
24            }
25        }
26    }
27
28    return result;
29}
0 / 22
012345startStackLegend:Not visitedVisitingVisitedCurrentResult: []