#include<iostream> #include<cstring> using namespace std; int main() { int a[100][100]={}, n, x, y, num=1, i=0; cin >> n; //memset(a, 0, sizeof(0)); x = 0, y = n-1; a[x][y] = num; while(num < n*n) { // 向下: while(x+1 < n && a[x+1][y] == 0) { num++; a[x+1][y] = num; i++; x++; } // x = 3, y = 3; // 向左: while(y-1 >= 0 && a[x][y-1]==0) { num++; a[x][y-1]=num; y--; i++; } // x = 3, y = 0; // 向上: while(x-1 >= 0 && a[x-1][y] == 0) { num++; a[x-1][y]=num; x--; i++; } // x = 0, y = 0; // 向右: while(y+1 < n && a[x][y+1]==0) { num++; a[x][y+1]=num; y++; i++; } //cout << x << " " << y << endl; if(i==n*n) break; } for(int i=0; i<=n-1; i++) { for(int j=0; j<=n-1; j++) { printf("%2d ", a[i][j]); } cout << endl; } return 0; }
标签:++,代码,int,while,num,蛇形,&&,100,方阵 From: https://www.cnblogs.com/dks0313/p/17310781.html