按照格式:"打印蛇形矩阵"
Sample Input
5
Sample Output:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
1716 15 14 13
Sample Input
7
Sample Output:
43 44 45 46 47 48 49
42 21 22 23 24 25 26
41 20 7 8 9 10 27
40 19 6 1 2 11 28
39 18 5 4 3 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31
解题思路:
按照数字的递增顺序,依次填充数值, 声明变量 index,从1......n*n 进行自增变化, 声明变量 x, y 两个指针,进行坐标位置的变化 , 清晰的思路,完成!
源码(java):
public class Main
{
public static void main(String[] args)
{
int n = 7;
int arr[][] = new int[n][n];
int x = n/2, y = n/2;
arr[x][y] = 1;
int index = 2;
for (int i = 0; i < n/2; i++)
{
y++;
for (int j = 0; j < (i+1)*2; j++) arr[x++][y] = index++;
x--;y--;
for (int j = 0; j < (i+1)*2; j++) arr[x][y--] = index++;
y++;x--;
for (int j = 0; j < (i+1)*2; j++) arr[x--][y] = index++;
x++;y++;
for (int j = 0; j < (i+1)*2; j++) arr[x][y++] = index++;
y--;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.printf("%-2d ", arr[i][j]);
}
System.out.println();
}
}
}