3 solutions
-
0
① 改变方向条件,越界或者已经访问过了,访问过就用vis数组记录为1
② 如果遍历四个方向,如果四个方向都走完都没有路可以走,就break;
易错点:不能把访问过的数字记录成0,因为矩阵里面可能有0的存在。(整了好久,才发现)
代码:
#include <bits/stdc++.h> using namespace std; int n, m, a[205][205], D[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; bool vis[205][205]; int main() { scanf("%d%d", &m, &n); for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) scanf("%d", &a[i][j]); int k = 0, num = 0, x = 1, y = 1; printf("%d ", a[x][y]); vis[x][y] = 1; while (true) { int xx = x + D[k][0], yy = y + D[k][1]; while ((xx < 1 || xx > m || yy < 1 || yy > n || vis[xx][yy]) && num < 5) { k += 1; k %= 4; xx = x + D[k][0], yy = y + D[k][1]; num += 1; } if (num >= 5) break; x = xx, y = yy; printf("%d ", a[xx][yy]); vis[xx][yy] = 1; num = 0; } return 0; }
Information
- ID
- 1176
- Time
- 1000ms
- Memory
- 512MiB
- Difficulty
- 8
- Tags
- # Submissions
- 39
- Accepted
- 8
- Uploaded By