每个颜色的折线表示一次大循环。 看图可知,这样难免会发生越界的情况, 所以给数组元素赋值时加个判断条件, 当行号和列号都不超过n时赋值,超过n时则不赋。 row为行号, col为列号, count为计数器,是每次给元素赋的值。
int main()
{
int n;
scanf("%d", &n);
int count = 1;
int row = 0;
int col = 0;
int arr[1000][1000] = {0};
while(count <= n*n)
{
for(int i=0; i<2; i++)
{
if(row<n && col<n)
arr[row][col] = count++;
col++;
}
col--;
while(col)
{
row++;
col--;
if(row<n && col<n)
arr[row][col] = count++;
}
row++;
while(row)
{
if(row<n && col<n)
arr[row][col] = count++;
row--;
col++;
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
return 0;
}