【算法】广度优先遍历 (BFS)

妖狐艹你老母 2023-10-07 22:41 158阅读 0赞

目录

  • 1.概述
  • 2.代码实现
  • 3.应用

1.概述

(1)广度优先遍历 (Breadth First Search),又称宽度优先遍历,是最简便的图的搜索算法之一。

(2)已知图 G = (V, E) 和一个源顶点 start,宽度优先搜索以一种系统的方式探寻 G 的边,从而“发现” start 所能到达的所有顶点,并计算 start 到所有这些顶点的距离(最少边数),该算法同时能生成一棵根为 start 且包括所有可达顶点的广度优先树。对从 start 可达的任意顶点 v,广度优先树中从 start 到 v 的路径对应于图 G 中从 start 到 v 的最短路径,即包含最小边数的路径。该算法对有向图无向图同样适用。

(3)之所以称之为广度优先遍历,是因为算法自始至终一直通过已找到和未找到顶点之间的边界向外扩展,就是说,算法首先搜索和 start 距离为 k 的所有顶点,然后再去搜索和 start 距离为 k + 1 的其他顶点。

2.代码实现

(1)当使用邻接矩阵来表示图时,其代码实现如下:

  1. class Solution {
  2. /*
  3. adjMatrix 为邻接矩阵,adjMatrix[i][j] = 0 表示节点 i 和 j 之间没有边直接相连
  4. start 为遍历的起点
  5. */
  6. public void bfs(int[][] adjMatrix, int start) {
  7. // n 表示图中的节点数量,节点编号为 0 ~ n - 1
  8. int n = adjMatrix.length;
  9. //定义 visited 数组,防止对节点进行重复遍历
  10. boolean[] visited = new boolean[n];
  11. Queue<Integer> queue = new LinkedList<>();
  12. if (start < 0 || start > n - 1) {
  13. System.out.println("起点编号应为 [0, " + (n - 1) + "] 之间的整数!");
  14. return;
  15. }
  16. //起点入队
  17. queue.offer(start);
  18. //标记起点
  19. visited[start] = true;
  20. System.out.print(start + " ");
  21. while (!queue.isEmpty()) {
  22. int node = queue.poll();
  23. //将与节点 node 相连的节点加入到 queue 中
  24. for (int i = 0; i < n; i++) {
  25. if (adjMatrix[node][i] != 0 && !visited[i]) {
  26. System.out.print(i + " ");
  27. visited[i] = true;
  28. queue.offer(i);
  29. }
  30. }
  31. }
  32. }
  33. }

(2)当使用邻接表来表示图时,其代码实现如下:

  1. class Solution {
  2. /*
  3. adjList 为邻接表,adjList[i] 中存储与节点 i 相邻的节点
  4. start 为遍历的起点
  5. */
  6. public void bfs(List<Integer>[] adjList, int start) {
  7. // n 表示图中的节点数量,节点编号为 0 ~ n - 1
  8. int n = adjList.length;
  9. //定义 visited 数组,防止对节点进行重复遍历
  10. boolean[] visited = new boolean[n];
  11. Queue<Integer> queue = new LinkedList<>();
  12. if (start < 0 || start > n - 1) {
  13. System.out.println("起点编号应为 [0, " + (n - 1) + "] 之间的整数!");
  14. return;
  15. }
  16. //起点入队
  17. queue.offer(start);
  18. //标记起点
  19. visited[start] = true;
  20. System.out.print(start + " ");
  21. while (!queue.isEmpty()) {
  22. int node = queue.poll();
  23. //将与节点 node 相连的节点加入到 queue 中
  24. for (int nextNode : adjList[node]) {
  25. while (!visited[nextNode]) {
  26. System.out.print(nextNode + " ");
  27. visited[nextNode] = true;
  28. queue.offer(nextNode);
  29. }
  30. }
  31. }
  32. }
  33. }

(3)下面以图 G 为例来说明:

在这里插入图片描述

① 构造邻接矩阵:

  1. int[][] adjMatrix = {
  2. {
  3. 0, 1, 1, 0, 1},
  4. {
  5. 1, 0, 0, 1, 1},
  6. {
  7. 1, 0, 0, 0, 1},
  8. {
  9. 0, 1, 0, 0, 1},
  10. {
  11. 1, 1, 1, 1, 0}
  12. };

② 构造邻接表:

  1. int n = 5;
  2. List<Integer>[] adjList = new ArrayList[n];
  3. for (int i = 0; i < n; i++) {
  4. adjList[i] = new ArrayList<>();
  5. }
  6. adjList[0].add(1);
  7. adjList[0].add(2);
  8. adjList[0].add(4);
  9. adjList[1].add(0);
  10. adjList[1].add(3);
  11. adjList[1].add(4);
  12. adjList[2].add(0);
  13. adjList[2].add(4);
  14. adjList[3].add(1);
  15. adjList[3].add(4);
  16. adjList[4].add(0);
  17. adjList[4].add(1);

如果 start = 2,那么遍历的节点依次为:

  1. 2 0 4 1 3

遍历过程如下图所示:
在这里插入图片描述

(4)无论是邻接表还是邻接矩阵的存储方式,BFS 算法都需要借助一个辅助队列 queue,n 个顶点均需入队一次,在最坏的情况下,空间复杂度为 O(|V|),而时间复杂度与图的存储方式有关:

  • 采用邻接矩阵存储方式时,查找每个顶点的邻接点所需的时间为O(|V|),故算法总的时间复杂度为 O(|V|2);
  • 采用邻接表存储方式时,每个顶点均需搜索一次(或入队一次),故时间复杂度为 O(|V|),在搜索任一顶点的邻接点时,每条边至少访问一次,故时间复杂度为 O(|E|),算法总的时间复杂度为 O(|V| + |E|);

3.应用

(1)除了对图进行遍历以外,BFS 在求解最短路径或者最短步数上有很多的应用。

(2)LeetCode 中的934.最短的桥这题便是对 BFS 的应用:

在这里插入图片描述

思路如下:
① 通过遍历找到数组 grid 中的 1 后进行广度优先搜索,此时可以得到第一座岛的位置集合,记为 island,并将其位置全部标记为 −1。
② 从 island 中的所有位置开始进行 BFS,当它们到达了任意的 1 时,即表示搜索到了第二个岛,搜索的层数就是答案。

代码实现如下:

  1. class Solution {
  2. public int shortestBridge(int[][] grid) {
  3. int n = grid.length;
  4. // dirs 记录遍历的四个方向
  5. int[][] dirs = {
  6. {
  7. -1, 0}, {
  8. 1, 0}, {
  9. 0, 1}, {
  10. 0, -1}};
  11. List<int[]> island = new ArrayList<>();
  12. Queue<int[]> queue = new ArrayDeque<>();
  13. for (int i = 0; i < n; i++) {
  14. for (int j = 0; j < n; j++) {
  15. if (grid[i][j] == 1) {
  16. queue.offer(new int[]{
  17. i, j});
  18. grid[i][j] = -1;
  19. while (!queue.isEmpty()) {
  20. int[] land = queue.poll();
  21. int x = land[0];
  22. int y = land[1];
  23. island.add(land);
  24. for (int k = 0; k < 4; k++) {
  25. int nextX = x + dirs[k][0];
  26. int nextY = y + dirs[k][1];
  27. if (nextX >= 0 && nextY >= 0 && nextX < n && nextY < n && grid[nextX][nextY] == 1) {
  28. queue.offer(new int[]{
  29. nextX, nextY});
  30. //标记 (nextX, nextY),表示已经访问过该点
  31. grid[nextX][nextY] = -1;
  32. }
  33. }
  34. }
  35. /*
  36. (1) 此时已经找到了题目中描述的两座岛中的一座,并且组成岛的每块陆地的坐标位置都保存在 island 中。
  37. (2) 从 island 中的所有坐标位置开始进行 BFS,当它们达到了任意的 1 时,即表示搜索到了第二座岛,
  38. 此时搜索的层数即为答案,在下面的代码中使用 step 来记录。
  39. */
  40. for (int[] land : island) {
  41. queue.offer(land);
  42. }
  43. int step = 0;
  44. while (!queue.isEmpty()) {
  45. int size = queue.size();
  46. for (int k = 0; k < size; k++) {
  47. int[] land = queue.poll();
  48. int x = land[0];
  49. int y = land[1];
  50. for (int d = 0; d < 4; d++) {
  51. int nextX = x + dirs[d][0];
  52. int nextY = y + dirs[d][1];
  53. if (nextX >= 0 && nextY >= 0 && nextX < n && nextY < n) {
  54. if (grid[nextX][nextY] == 0) {
  55. queue.offer(new int[]{
  56. nextX, nextY});
  57. //标记 (nextX, nextY),表示已经访问过该点
  58. grid[nextX][nextY] = -1;
  59. } else if (grid[nextX][nextY] == 1) {
  60. return step;
  61. }
  62. }
  63. }
  64. }
  65. step++;
  66. }
  67. }
  68. }
  69. }
  70. return 0;
  71. }
  72. }

(3)大家可以去 LeetCode 上找相关的 BFS 的题目来练习,或者也可以直接查看LeetCode算法刷题目录(Java)这篇文章中的 BFS 章节。如果大家发现文章中的错误之处,可在评论区中指出。

发表评论

表情:
评论列表 (有 0 条评论,158人围观)

还没有评论,来说两句吧...

相关阅读