要求將制定矩陣蛇形填充,最後結果如下
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
如果不仔細考慮的話,代碼可能是這樣的
代碼囉嗦,而且還是不正確的
指針回調時,邊界在不斷縮小的,所以固定判斷-1和n是不正確的。
int m = 0;
int x = n - 1;
int y = 0;
while (m < n*n) {
while (y < n && a[x][y] == 0) a[x][y++] = ++m;
if (y == n) y--;
x--;
while (x >= 0 && a[x][y] == 0) a[x--][y] = ++m;
if (x == -1) x++;
y--;
while (y >= 0 && a[x][y] == 0) a[x][y--] = ++m;
if (y == -1) y++;
x++;
while (x < n && a[x][y] == 0) a[x++][y] = ++m;
if (x == n) x--;
y++;
}
}
這題思路正確的話,很能展現c語言的簡潔。
關鍵點是
1.先設置起點初始值
2.移動時,先預判,再移動
另外,座標的方向是由輸出代碼循環的方向決定的
int n = 4;
int a[4][4];
memset(a, 0, sizeof(a));
int m, x, y;
m = a[x = 0][y = n - 1] = 1;
while (m < n*n) {
while (x + 1 < n && !a[x+1][y]) a[++x][y] = ++m;
while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++m;
while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++m;
while (y + 1 < n && !a[x][y + 1])a[x][++y] = ++m;
}
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++) {
printf("%2d ", a[i][j]);
}
printf("\n");
}