[关闭]
@Dmaxiya 2020-12-12T15:35:14.000000Z 字数 10043 阅读 1075

深度优先搜索

Hello_World


dfs

深度优先搜索 简称 /深搜,简单来说就是优先往“下一状态”进行搜索,在当前状态下,如果有下一步,就先搜索它的下一个状态,而不是并列状态,优先搜索并列状态的是 (宽度优先搜索),这个后面再说。

1. 树上 dfs

先从最简单的树上 开始,基本算法是从根节点出发,往第一个子节点搜索,如果子节点仍有子节点,则继续搜索子节点,直到叶子节点,再返回上一层,继续搜索上一层的第二个子节点,不断回溯直到搜索到最后一个叶子节点
如下图,其 顺序为


rVRA0A.png

其中括号中的节点没有被重复搜索,只是深搜时回溯的顺序。将以上序列去掉括号中的节点,再按顺序将 分别记为 ,就是这张图的 序, 序可以通过一次深搜得到,由于 序所具有的一些性质,其在 、线段树构图等算法中有重要作用,这还需在学习 表、线段树等知识后再讲解,这里不进行展开。
有向树(只存在从父节点指向子节点的边)上搜索代码如下:

  1. void dfs(int x) {
  2. /*当前节点 x 初始化操作*/
  3. int len = G[x].size();
  4. for(int i = 0; i < len; ++i) {
  5. int pos = G[x][i];
  6. /*更新 pos 节点前的操作*/
  7. dfs(pos);
  8. /*更新 pos 节点后的操作*/
  9. }
  10. /*遍历所有子节点后对 x 节点有关的操作*/
  11. }

无向树(每条边都有两个方向)上搜索代码如下:

  1. void dfs(int f, int x) {
  2. // f 为当前节点 x 的父节点
  3. /*对 x 节点初始化操作*/
  4. int len = G[x].size();
  5. for(int i = 0; i < len; ++i) {
  6. int pos = G[x][i];
  7. if(pos != f) {
  8. /*更新 pos 节点前的操作*/
  9. dfs(x, pos);
  10. /*更新 pos 节点后的操作*/
  11. }
  12. }
  13. /*遍历所有子节点后对 x 节点有关的操作*/
  14. }

现在看起来文字描述比较多,只是因为还没有讲到图在计算机上的储存方式,做到有关图上算法的练习后,会更新上面的代码。
其实对于有向树上的 操作也可以用无向树上 操作的代码,两种写法区别不大,理解一种自然理解了另一种。

2. 图上 dfs

树有一个很重要的性质是没有环,没有环的图就是一棵树。
图上的 算法步骤和树上 一模一样,只是由于图上存在环,所以需要加一个 数组,表示当前节点已经被搜索过,不再进行搜索,如果不用 数组进行标记,深搜算法将一直在环上搜索。
下面这张图从 节点开始 的顺序(为体现 数组的作用,下面的序列采用了一种比较奇怪的顺序进行深搜)如下(括号中的节点为已经 过,不再进行搜索的节点,序列不包含回溯节点):



  1. void dfs(int x) {
  2. /*当前节点 x 初始化操作*/
  3. vis[x] = true;
  4. int len = G[x].size();
  5. for(int i = 0; i < len; ++i) {
  6. int pos = G[x][i];
  7. if(!vis[pos]) {
  8. /*更新 pos 节点前的操作*/
  9. dfs(pos);
  10. /*更新 pos 节点后的操作*/
  11. }
  12. }
  13. /*遍历所有子节点后对 x 节点有关的操作*/
  14. }

无论是有向图还是无向图,深搜代码都相同,因为有向图上仍然存在类似 的环,树是一种特殊的图,所以树上搜索也可以用这一段代码,但是建议图上 与树上 代码分开理解,因为树上有许多性质是图上所没有的。

4. 解空间的 dfs

深度优先搜索不但可以应用在图上,也可以在解空间上进行搜索,可以将每一个状态看成一个节点,一般解空间的搜索是在一棵树上进行的,每一个解的状态可以衍生出后继的几个状态,但通常不会搜索到之前的状态。
解空间的深搜代码如下:

  1. void dfs(/*当前状态*/) {
  2. if(/*搜索到最终状态*/) {
  3. /*判断解是否合法,并做相应操作*/
  4. return ;
  5. }
  6. for(/*搜索所有后继状态*/) {
  7. if(/*该后继状态合法*/) {
  8. /*改变为后继状态*/
  9. dfs(/*该后继状态*/)
  10. /*修改为当前状态*/
  11. }
  12. }
  13. }

这是解空间 的基本模板,一般题目的深搜直接套用就行,但是在写的时候一定要注意每一步是否考虑到了,即使上面的某一步在代码中不必写到,但是写的时候一定要思考是否可以省略这一步,不能去想是否要加上这一步,从第二个方向考虑,容易因为漏考虑某些情况而省略代码。

2 月 8 日 dfs 练习题解

A. N皇后问题

题解

皇后问题,只要用一个大小为 的一维数组, 表示第 行的皇后放在第 列的位置就可以表示所有的状态,而且判断皇后位置是否合法也比二维数组更加容易。
深搜思路为:从第 行开始搜索,对于第 行的第 列,判断是否存在 ,第一个不等号是用来判断前面几行中是否存在放置在 列的皇后,第二个不等号是用来判断是否存在与第 个皇后互为对角线的皇后,知道搜索到第 行,说明这种情况是合法的,答案

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const int maxn = 100;
  21. int n;
  22. int num[maxn];
  23. int put[maxn];
  24. bool judge(int x, int y) {
  25. for(int i = 0; i < x; ++i) {
  26. if(put[i] == y || abs(x - i) == abs(y - put[i])) {
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32. void dfs(int depth, int n) {
  33. if(depth == n) {
  34. ++num[n];
  35. return ;
  36. }
  37. for(int i = 0; i < n; ++i) {
  38. if(judge(depth, i)) {
  39. put[depth] = i;
  40. dfs(depth + 1, n);
  41. }
  42. }
  43. }
  44. int main() {
  45. #ifdef LOCAL
  46. freopen("test.txt", "r", stdin);
  47. // freopen("out.txt", "w", stdout);
  48. #endif // LOCAL
  49. ios::sync_with_stdio(false);
  50. for(int i = 1; i <= 10; ++i) {
  51. dfs(0, i);
  52. }
  53. while(scanf("%d", &n), n != 0) {
  54. printf("%d\n", num[n]);
  55. }
  56. return 0;
  57. }

B. Sudoku Killer

题解

从第一个数字开始搜索,对于每一个问号,对其尝试填入 ,如果存在一个合法的可以填入的数字(当前行、列、九宫格不存在与其相等的数字),就将该数字填入,并继续往下一格搜索。直到搜索到最后一格。
程序中运用了一些行列下标运算的技巧,将二维 与一个数字 进行一一映射,这样就可以直接从 进行搜索,而不需要每行末尾的判断。

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const int maxn = 20;
  21. char str[maxn][maxn];
  22. int num[maxn][maxn];
  23. int cas = 0;
  24. bool flag;
  25. bool judge(int x, int y, int n) {
  26. for(int i = 0; i < 9; ++i) {
  27. if(num[i][y] == n || num[x][i] == n) {
  28. return false;
  29. }
  30. }
  31. int xx = x / 3 * 3;
  32. int yy = y / 3 * 3;
  33. for(int i = 0; i < 3; ++i) {
  34. for(int j = 0; j < 3; ++j) {
  35. if(num[xx + i][yy + j] == n) {
  36. return false;
  37. }
  38. }
  39. }
  40. return true;
  41. }
  42. void dfs(int depth) {
  43. if(depth == 81) {
  44. flag = true;
  45. return ;
  46. }
  47. int x = depth / 9;
  48. int y = depth % 9;
  49. if(num[x][y] == 0) {
  50. for(int i = 1; i <= 9; ++i) {
  51. if(judge(x, y, i)) {
  52. num[x][y] = i;
  53. dfs(depth + 1);
  54. if(flag) {
  55. return ;
  56. }
  57. num[x][y] = 0;
  58. }
  59. }
  60. } else {
  61. dfs(depth + 1);
  62. }
  63. }
  64. int main() {
  65. #ifdef LOCAL
  66. freopen("test.txt", "r", stdin);
  67. // freopen("out.txt", "w", stdout);
  68. #endif // LOCAL
  69. ios::sync_with_stdio(false);
  70. while(scanf("%s", str[0]) != EOF) {
  71. if(cas != 0) {
  72. printf("\n");
  73. }
  74. ++cas;
  75. flag = false;
  76. for(int i = 1; i < 9; ++i) {
  77. scanf("%s", str[0] + i);
  78. }
  79. for(int i = 1; i < 9; ++i) {
  80. for(int j = 0; j < 9; ++j) {
  81. scanf("%s", str[i] + j);
  82. }
  83. }
  84. for(int i = 0; i < 9; ++i) {
  85. for(int j = 0; j < 9; ++j) {
  86. if(str[i][j] == '?') {
  87. num[i][j] = 0;
  88. } else {
  89. num[i][j] = str[i][j] - '0';
  90. }
  91. }
  92. }
  93. dfs(0);
  94. for(int i = 0; i < 9; ++i) {
  95. for(int j = 0; j < 9; ++j) {
  96. if(j != 0) {
  97. printf(" ");
  98. }
  99. printf("%d", num[i][j]);
  100. }
  101. printf("\n");
  102. }
  103. }
  104. return 0;
  105. }

C. 连连看

题解

这题相对于一般的路径搜索多了一个:最多转弯两次的限制,实际上这题和一般搜索的代码完全相同,只是在判断时多加一个转弯次数的判断罢了,如果转弯次数超过两次,直接返回“不可行”,否则继续搜索下一层,对于每一个“下一层”的搜索,只要存在一个“可行”的路径,当前状态就是可行的,只有所有后继状态都不可行时,当前状态才是不可行的。
对于初始位置,应将方向初始化为与四个方向都不相同的方向,并将方向改变的次数初始化为

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const int maxn = 1000 + 100;
  21. int n, m, q;
  22. int xx1, yy1, xx2, yy2;
  23. int num[maxn][maxn];
  24. const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
  25. int judge(int x, int y) {
  26. if(x < 1 || x > n || y < 1 || y > m) {
  27. return 0;
  28. }
  29. if(x == xx2 && y == yy2) {
  30. return 1;
  31. }
  32. if(num[x][y] != 0) {
  33. return 0;
  34. } else {
  35. return -1;
  36. }
  37. }
  38. bool dfs(int x, int y, int d, int cnt) {
  39. if(cnt == 3) {
  40. return false;
  41. }
  42. if(x == xx2 && y == yy2) {
  43. return true;
  44. }
  45. bool flag = false;
  46. for(int i = 0; i < 4; ++i) {
  47. int xx = x + dir[i][0];
  48. int yy = y + dir[i][1];
  49. int tmp = judge(xx, yy);
  50. if(tmp != 0) {
  51. if(tmp == -1) {
  52. num[xx][yy] = -1;
  53. }
  54. if(i != d) {
  55. if(dfs(xx, yy, i, cnt + 1)) {
  56. flag = true;
  57. }
  58. } else {
  59. if(dfs(xx, yy, i, cnt)) {
  60. flag = true;
  61. }
  62. }
  63. if(tmp == -1) {
  64. num[xx][yy] = 0;
  65. }
  66. if(flag) {
  67. break;
  68. }
  69. }
  70. }
  71. return flag;
  72. }
  73. int main() {
  74. #ifdef LOCAL
  75. freopen("test.txt", "r", stdin);
  76. // freopen("out.txt", "w", stdout);
  77. #endif // LOCAL
  78. ios::sync_with_stdio(false);
  79. while(scanf("%d%d", &n, &m), n != 0 || m != 0) {
  80. for(int i = 1; i <= n; ++i) {
  81. for(int j = 1; j <= m; ++j) {
  82. scanf("%d", &num[i][j]);
  83. }
  84. }
  85. scanf("%d", &q);
  86. for(int i = 0; i < q; ++i) {
  87. scanf("%d%d%d%d", &xx1, &yy1, &xx2, &yy2);
  88. if(num[xx1][yy1] != num[xx2][yy2] || num[xx1][yy1] == 0 || num[xx2][yy2] == 0) {
  89. printf("NO\n");
  90. continue;
  91. }
  92. if(dfs(xx1, yy1, -1, -1)) {
  93. printf("YES\n");
  94. } else {
  95. printf("NO\n");
  96. }
  97. }
  98. }
  99. return 0;
  100. }

2 月 9 - 10 日 dfs 练习

A. Red and Black

题意

一个 的网格中,一个人在 字符所在的位置,他可以向上下左右四个方向走动,且他只能走在 的格子上,不能穿过 的格子,问他可以到达的方格数量,输入到 结束。

数据范围

题解

点所在位置开始 ,将经过的点标记,对于每个位置搜索上下左右四个方向能够到达且没有呗标记的点,最后输出标记的点数。

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const int maxn = 50;
  21. int n, m, x, y, ans;
  22. char str[maxn][maxn];
  23. const int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
  24. bool in(int x, int y) {
  25. return (x >= 0 && x < n && y >= 0 && y < m);
  26. }
  27. void dfs(int x, int y) {
  28. for(int i = 0; i < 4; ++i) {
  29. int xx = x + dir[i][0];
  30. int yy = y + dir[i][1];
  31. if(in(xx, yy) && str[xx][yy] == '.') {
  32. ++ans;
  33. str[xx][yy] = '#';
  34. dfs(xx, yy);
  35. }
  36. }
  37. }
  38. int main() {
  39. #ifdef LOCAL
  40. freopen("test.txt", "r", stdin);
  41. // freopen("out.txt", "w", stdout);
  42. #endif // LOCAL
  43. ios::sync_with_stdio(false);
  44. while(scanf("%d%d", &m, &n), n != 0 || m != 0) {
  45. ans = 1;
  46. for(int i = 0; i < n; ++i) {
  47. scanf("%s", str[i]);
  48. for(int j = 0 ; j < m; ++j) {
  49. if(str[i][j] == '@') {
  50. x = i;
  51. y = j;
  52. }
  53. }
  54. }
  55. dfs(x, y);
  56. printf("%d\n", ans);
  57. }
  58. return 0;
  59. }

B. A 计划

题解

思路和上一题相同,只是多了一个时间 的限制(要在 时刻内解救公主),超过 步还没有拯救到公主,则不能沿这条路径拯救公主,以及到达 字格时,需要立即到另一层。

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const int maxn = 100;
  21. int T, n, m, t;
  22. bool flag;
  23. char str[2][maxn][maxn];
  24. bool vis[2][maxn][maxn];
  25. const int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
  26. bool in(int x, int y) {
  27. return x >= 0 && x < n && y >= 0 && y < m;
  28. }
  29. void dfs(int f, int x, int y, int t) {
  30. if(t == -1) {
  31. return ;
  32. }
  33. if(str[f][x][y] == 'P') {
  34. flag = true;
  35. return ;
  36. }
  37. int ff;
  38. for(int i = 0; i < 4; ++i) {
  39. int xx = x + dir[i][0];
  40. int yy = y + dir[i][1];
  41. if(in(xx, yy)) {
  42. if(str[f][xx][yy] == '#') {
  43. ff = 1 - f;
  44. } else {
  45. ff = f;
  46. }
  47. if(!vis[ff][xx][yy]) {
  48. vis[ff][xx][yy] = true;
  49. if(str[ff][xx][yy] == '.' || str[ff][xx][yy] == 'P') {
  50. dfs(ff, xx, yy, t - 1);
  51. if(flag) {
  52. return ;
  53. }
  54. }
  55. vis[ff][xx][yy] = false;
  56. }
  57. }
  58. }
  59. }
  60. int main() {
  61. #ifdef LOCAL
  62. freopen("test.txt", "r", stdin);
  63. // freopen("out.txt", "w", stdout);
  64. #endif // LOCAL
  65. ios::sync_with_stdio(false);
  66. scanf("%d", &T);
  67. while(T--) {
  68. flag = false;
  69. memset(vis, 0, sizeof(vis));
  70. scanf("%d%d%d", &n, &m, &t);
  71. for(int i = 0; i < 2; ++i) {
  72. for(int j = 0; j < n; ++j) {
  73. scanf("%s", str[i][j]);
  74. }
  75. }
  76. vis[0][0][0] = true;
  77. dfs(0, 0, 0, t);
  78. if(flag) {
  79. printf("YES\n");
  80. } else {
  81. printf("NO\n");
  82. }
  83. }
  84. return 0;
  85. }

C. 逃离迷宫

题解

过程中存一个转弯次数,搜索的时候,如果方向和原来的方向不一致,则转弯次数 ,如果转弯次数大于 ,则不能从这条路径到达目标。注意这题需要剪枝,一个是一次 过程中走过的路不能再走,一个是如果到达某个点时的转弯次数超过之前搜索到达这个点时的转弯次数,则不再进行搜索。

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const int maxn = 200;
  21. int T, n, m;
  22. int xx1, yy1, xx2, yy2;
  23. int cnt, k;
  24. bool flag;
  25. char str[maxn][maxn];
  26. bool vis[maxn][maxn];
  27. int ccnt[maxn][maxn];
  28. const int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
  29. bool in(int x, int y) {
  30. return x > 0 && x <= n && y > 0 && y <= m;
  31. }
  32. void dfs(int x, int y, int d, int cnt) {
  33. if(cnt > ccnt[x][y]) {
  34. return ;
  35. } else {
  36. ccnt[x][y] = cnt;
  37. }
  38. if(cnt == k + 1) {
  39. return ;
  40. }
  41. if(x == xx2 && y == yy2) {
  42. flag = true;
  43. return ;
  44. }
  45. for(int i = 0; i < 4; ++i) {
  46. int xx = x + dir[i][0];
  47. int yy = y + dir[i][1];
  48. if(in(xx, yy) && str[xx][yy] == '.' && !vis[xx][yy]) {
  49. vis[xx][yy] = true;
  50. if(i == d) {
  51. dfs(xx, yy, i, cnt);
  52. } else {
  53. dfs(xx, yy, i, cnt + 1);
  54. }
  55. vis[xx][yy] = false;
  56. if(flag) {
  57. return ;
  58. }
  59. }
  60. }
  61. }
  62. int main() {
  63. #ifdef LOCAL
  64. freopen("test.txt", "r", stdin);
  65. // freopen("out.txt", "w", stdout);
  66. #endif // LOCAL
  67. ios::sync_with_stdio(false);
  68. scanf("%d", &T);
  69. while(T--) {
  70. flag = false;
  71. memset(vis, 0, sizeof(vis));
  72. memset(ccnt, 0x3f, sizeof(ccnt));
  73. scanf("%d%d", &n, &m);
  74. for(int i = 1; i <= n; ++i) {
  75. scanf("%s", str[i] + 1);
  76. }
  77. scanf("%d%d%d%d%d", &k, &yy1, &xx1, &yy2, &xx2);
  78. dfs(xx1, yy1, -1, -1);
  79. if(flag) {
  80. printf("yes\n");
  81. } else {
  82. printf("no\n");
  83. }
  84. }
  85. return 0;
  86. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注