DFS And BFS
Thinking Patterns - DFS v.s. Backtrack
Problems - Islands Problems
Problems | Possible Solutions | Key Points | Code | Similar Problems | Comments |
---|---|---|---|---|---|
200. Number of Islands | dfs, bfs | code | |||
1254. Number of Closed Islands | dfs, bfs | code | |||
1905. Count Sub Islands | dfs, bfs, union-find | code | 1992 | ||
1020. Number of Enclaves | dfs, bfs | code | |||
694. Number of Distinct Islands | dfs, bfs | code | |||
695. Max Area of Island | dfs, bfs | code | |||
- |
Key Points
- 694
How to present the shape of islands with
BFS
andDFS
?
Complexity Analyze
- 200.
Time Complexity
- O(N+4N) = O(N) N = m*n
- Loop all the node outside, m*n
- Overall O(N)
Space Complexity
- For DFS, Recursive stack depth: worst at
O(N)
- For BFS, Queue length: worst at
O(N)
- Worst case example,
m=1, n = N, and all equals 1
- Use
grid
as visited, no extra spaces
- 1254, 1905, 1020, 694
Similar as 200
BFS
Thinking Patterns
BFS算法的本质就是二叉树的层序遍历。
衍生到多叉树的层序遍历,和图的遍历(增加visited数组)
BFS 算法经常用来求解最短路径问题。最短路径,都可以类比成二叉树最小深度问题(寻找距离根节点最近的叶子节点),递归遍历必须要遍历整棵树的所有节点才能找到目标节点,而层序遍历不需要遍历所有节点就能搞定,所以层序遍历适合解决最短路径问题。
BFS Problems
Problems | Possible Solutions | Key Points | Code | Similar Problems | Comments |
---|---|---|---|---|---|
773. Sliding Puzzle | bfs | code | |||
752. Open the Lock | bfs | code | |||
919. Complete Binary Tree Inserter | bfs | code | |||
841. Keys and Rooms | bfs | code | |||
433. Minimum Genetic Mutation | bfs | code | |||
1926. Nearest Exit from Entrance in Maze | bfs | code | |||
1091. Shortest Path in Binary Matrix | bfs | code | |||
994. Rotting Oranges | bfs | code | |||
721. Accounts Merge | bfs, dfs, union-find | bfs union-find |
|||
127. Word Ladder | bfs | bfs | |||
365. Water and Jug Problem | bfs | bfs | |||
- |
Complexity Analyze
Refer to the code