标签:while 多次 const else put ++i 方向 size inline
按照对角线填数。
1 2 6 7 15
3 5 8 14 16
4 9 13 17 22
10 12 18 21 23
11 19 20 24 25
x--,y++
x>=1 && y<=n
就能往上走x++,y--
int main(int argc, const char * argv[]) {
int n;
scanf("%d", &n);
int x,y,tot;
a[x=1][y=1] = tot = 1;
while (tot <= n*n) {
while (x >= 1 && y <= n) {
a[x--][y++] = tot++;
}
if (y == n+1) {
x +=2; y--;
} else {
x++;
}
while (x <= n && y >= 1) {
a[x++][y--] = tot++;
}
if (x == n+1) {
y += 2; x--;
} else {
y++;
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j)
printf("%5d", a[i][j]);
puts("");
}
return 0;
}
int main(int argc, const char * argv[]) {
int n;
scanf("%d", &n);
memset(a, -1, sizeof a);
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
a[i][j] = 0;
int x,y,tot, k = 0;
x = y = tot = 1;
while (tot <= n*n) {
a[x][y] = tot++;
if (tot > n*n) break;
// 循环, 边缘需要多次转向
while (a[x+dx[k]][y+dy[k]] != 0) {
k++;
k %= 4;
}
x = x+dx[k];
y = y+dy[k];
//**右 || 下 只走一次,走完转向
if (k==0 || k==2) k++;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j)
printf("%5d", a[i][j]);
puts("");
}
return 0;
}
标签:while 多次 const else put ++i 方向 size inline
原文地址:https://www.cnblogs.com/i-8023-/p/12634602.html