12 graph (BFS)
Last updated
Was this helpful?
Last updated
Was this helpful?
这里主要是讲些图相关的bfs和dfs题,还有就是topological sort了。bfs主要就是用个Queue,dfs就是递归搜索了。BFS的时间复杂度都是O(m+n),m是边数,n是点数
技巧:
如果是矩阵的话可以用 i * m + j来避免用pair class
上面那个其实很难记住,某次pramp的时候,某亚洲面孔小哥哥,指了条名路。可以用int[] .Queue<int[]> q = new LinkedList<>(); q.add(new int[]{i, j});
搜的时候可以考虑用direction matrix, int[] x = {0, 0, 1, -1}, int[] y = {1, -1, 0, 0},然后loop k 从 0 -- 4
如果是扫雷那样8个方向的话,用这个
BFS / DFS :
- 也可以用union find来做&DFS (130)
(L433) - BFS/DFS/Union Find
-- 跟几乎一样,还是bfs/dfs/union find都能解
- 还可以用bfs,不过2分比较好 (L600)
--与有点关系
399 Evaluate Division
417 Pacific Atlantic Water Flow
490 The Maze
505 The Maze II
499 The Maze III
332 Reconstruct Itinerary
Special BFS node:
Topological Sort:
曼哈顿距离:
296 Best Meeting Point
other related:
407 Trapping Rain Water II -- heap
(L573 Build Post Office II)
- can use bfs or dfs or union find as well (求联通块里具体有什么node) (323 Number of Connected Components in an Undirected Graph -- 求联通块个数)
-- dfs
-- dfs / union find
- bfs with backtrack, Uber
-- Dijkstra (BFS)
-- 还有dp解法
-- 之前是用背包解,然后数学解法是四平方定理,然后还能递归,还有另一种DP解法。太高级,有空再补
(L120)
(L121)
-- 变体
(L615)
(L616)
(L605)
(L434) - Union Find
-- Union Find
-- similar to 296 Best Meeting Point, 这题不一定有解,所以不能用296的方法-- 曼哈顿距离