二维数组的遍历
2023-11-16 21:21:55
发布于:广东
21阅读
0回复
0点赞
读入数据,接着对其进行多个方向遍历即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 1001;
int g[N][N];
int main()
{
int n, m;
cin >> n >> m;
int t = 0;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
g[i][j] = ++ t;
int r = 1, c = 1;
cout << g[r][c];
g[r][c] = 0;
for(int i = 2; i <= n * m; i ++)
{
while(r + 1 <= n && g[r + 1][c])
{
cout << "," << g[++ r][c];
g[r][c] = 0;
}
while(c + 1 <= m && g[r][c + 1])
{
cout << "," << g[r][++ c];
g[r][c] = 0;
}
while(r - 1 >= 1 && g[r - 1][c])
{
cout << "," << g[-- r][c];
g[r][c] = 0;
}
while(c - 1 >= 1 && g[r][c - 1])
{
cout << "," << g[r][-- c];
g[r][c] = 0;
}
}
return 0;
}
这里空空如也
有帮助,赞一个