Explanation of runtimes of BFS and DFS

后端 未结 5 449
你的背包
你的背包 2021-01-30 08:42

Why are the running times of BFS and DFS O(V+E), especially when there is a node that has a directed edge to a node that can be reached from the vertex, like in this example in

5条回答
  •  执念已碎
    2021-01-30 09:28

    You iterate over the |V| nodes, for at most |V| times. Since we have an upper bound of |E| edges in total in the graph, we will check at most |E| edges. Different vertices will have varying number of adjacent nodes, so we cannot just multiply |V|*|E| (it means that for each vertex, we traverse |E| edges, which is not true, |E| is the total number of edges over all nodes), rather, we check over V nodes, and we check over a total of E edges. At the end, we have O(|V|+|E|)

    For DFS, it's something similar, we loop through all of a vertices adjacency lists, calling DFS(v) if it's not been visited, meaning that we incur |V| time steps, plus the time incurred to visit adjacent nodes (essentially, these form an edge, and we have a total of |E| edges, hence, O(V+E) time.

        private static void visitUsingDFS(Node startNode) {
            if(startNode.visited){
                return;
            }
            startNode.visited = true;
            System.out.println("Visited "+startNode.data);
            for(Node node: startNode.AdjacentNodes){
                if(!node.visited){
                    visitUsingDFS(node);
                }
            }
        }
    

提交回复
热议问题