Advertisement
Dmaxiya

数字接龙 参考代码

Mar 18th, 2025
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 20;
  6. int n, k;
  7. bool flag;
  8. int num[maxn][maxn], ans[maxn * maxn];
  9. bool vis[maxn][maxn], crossVis[maxn][maxn][maxn][maxn];
  10. const int dir[8][2] = {
  11.     {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}
  12. };
  13.  
  14. bool in(int x, int y) {
  15.     return x >= 0 && x < n && y >= 0 && y < n;
  16. }
  17.  
  18. bool cross(int x, int y, int idx) {
  19.     int x1 = x + dir[(idx + 1) % 8][0];
  20.     int y1 = y + dir[(idx + 1) % 8][1];
  21.     int x2 = x + dir[(idx + 7) % 8][0];
  22.     int y2 = y + dir[(idx + 7) % 8][1];
  23.     return in(x1, y1) && in(x2, y2) && (crossVis[x1][y1][x2][y2] || crossVis[x2][y2][x1][y1]);
  24. }
  25.  
  26. void dfs(int x, int y, int kk, int depth) {
  27.     if (depth == n * n - 1) {
  28.         if (x == n - 1 && y == n - 1) {
  29.             flag = true;
  30.             for (int i = 0; i < depth; ++i) {
  31.                 cout << ans[i];
  32.             }
  33.             cout << endl;
  34.         }
  35.         return ;
  36.     }
  37.     for (int i = 0; i < 8; ++i) {
  38.         int xx = x + dir[i][0];
  39.         int yy = y + dir[i][1];
  40.         if (in(xx, yy) && !vis[xx][yy] && num[xx][yy] == kk) {
  41.             if (i % 2 == 1 && cross(x, y, i)) {
  42.                 continue;
  43.             }
  44.             ans[depth] = i;
  45.             vis[xx][yy] = true;
  46.             crossVis[x][y][xx][yy] = true;
  47.             dfs(xx, yy, (kk + 1) % k, depth + 1);
  48.             vis[xx][yy] = false;
  49.             crossVis[x][y][xx][yy] = false;
  50.             if (flag) {
  51.                 return ;
  52.             }
  53.         }
  54.     }
  55. }
  56.  
  57. int main() {
  58. #ifdef ExRoc
  59.     freopen("test.txt", "r", stdin);
  60. #endif
  61.     ios::sync_with_stdio(false);
  62.  
  63.     cin >> n >> k;
  64.     for (int i = 0; i < n; ++i) {
  65.         for (int j = 0; j < n; ++j) {
  66.             cin >> num[i][j];
  67.         }
  68.     }
  69.     vis[0][0] = true;
  70.     dfs(0, 0, 1 % k, 0);
  71.     if (!flag) {
  72.         cout << -1 << endl;
  73.     }
  74.  
  75.     return 0;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement