Build a graph before DFS

Use

        List<Integer>[] graph = new List[n];
        for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();
        
        for(int[] connection : connections){
           graph[connection[0]].add(connection[1]);
           graph[connection[1]].add(connection[0]);
        }
        

To build a graph, where n is the total amount of node.

Last updated

Was this helpful?