题目要求
1 2 3 4 5 6 7 8 9 10 11
| Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example, Given n = 3,
You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
|
也就是将递加的数字按照顺时针的顺序依次填入数组之中
这道题目联系到Spiral Matrix I,其实就相当好解决了。Spiral Matrix I可以参考我的这篇博客
具体代码
在参考完这篇博客后,就会发现,这里其实就是将读取数据反过来改为填入数据,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public int[][] generateMatrix(int n) { int[][] result = new int[n][n]; int rowStart = 0; int rowEnd = n-1; int colStart = 0; int colEnd = n-1; int number = 1; while(rowStart<=rowEnd && colStart<=colEnd){ for(int i = colStart ; i<=colEnd ; i++){ result[rowStart][i] = number; number++; } rowStart++; for(int i = rowStart ; i<=rowEnd ; i++){ result[i][colEnd] = number; number++; } colEnd--; if(rowStart <= rowEnd){ for(int i = colEnd ; i>=colStart ; i--){ result[rowEnd][i] = number; number++; } } rowEnd--; if(colStart<= colEnd){ for(int i = rowEnd ; i>= rowStart ; i--){ result[i][colStart] = number; number++; } } colStart++; } return result; }
|