Graphs data structure: DFS vs BFS?

≡放荡痞女 提交于 2019-11-29 19:40:10

BFS is going to use more memory depending on the branching factor... however, BFS is a complete algorithm... meaning if you are using it to search for something in the lowest depth possible, BFS will give you the optimal solution. BFS space complexity is O(b^d)... the branching factor raised to the depth (can be A LOT of memory).

DFS on the other hand, is much better about space however it may find a suboptimal solution. Meaning, if you are just searching for a path from one vertex to another, you may find the suboptimal solution (and stop there) before you find the real shortest path. DFS space complexity is O(|V|)... meaning that the most memory it can take up is the longest possible path.

They have the same time complexity.

In terms of implementation, BFS is usually implemented with Queue, while DFS uses a Stack.

breadth first searches for siblings first. depth first obviously searches for children first. So, I guess it would depend on what kind of searching you're looking to do. relationship type searches across fields would probably lend itself to bfs, where hierarchical (trees, folders, ranks, etc) would be more suited as a dfs.

Both the graph traversals promises one thing: a complete traversal of the graph, visiting every vertex in the graph. If you don't have memory contraints, DFS is a good choice, as BFS takes up a lot of space. So, choosing between these two depends on your requirement.

Wanna find the (strongly/)connected components of the graph? or solve the maze or sudoku? Use DFS. If you look closely, the Pre-Order, Post-Order and In-Order are all variants of the DFS. So, yes, that's some interesting applications.

BFS if you want to test if a graph is bipartite, find the shortest path between two nodes or applications that require such tasks.

anshu shrivastavs

In bfs queue is used while in dfs stack is used to store vertices according to graph traversal.
2- in bfs process is done level to level (according to directed or non directed graph) while in dfs the process is done to depth (the process of first visiting the root node and another is do far and then apply backtracking from last node to root node).

BFS is extremely good for shortest paths while DFS is not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!