原理很簡單,從外面開始往裏面循環輸出
要注意的是
- 需要有標記,純座標運算太容易出錯
- 記錄輸出的個數,退出循環
- 對於一圈循環,分別模擬向四個方向
#include<cstdio>
int main() {
int n, m, a[205][205];
scanf("%d %d", &m, &n);
int num = n * m;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
int tot = 0, x = -1, y = 0;
while(tot < n*m) {
while(x+1<m && a[x+1][y]!=-1) {
printf("%d ", a[++x][y]);
a[x][y] = -1;
tot++;
}
while(y+1<n && a[x][y+1]!=-1) {
printf("%d ", a[x][++y]);
a[x][y] = -1;
tot++;
}
while(x-1>=0 && a[x-1][y]!=-1) {
printf("%d ", a[--x][y]);
a[x][y] = -1;
tot++;
}
while(y-1>=0 && a[x][y-1]!=-1) {
printf("%d ", a[x][--y]);
a[x][y] = -1;
tot++;
}
}
return 0;
}