Spiral Matrix II
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 ] ]
思路: 控制好边界条件
- public int[][] generateMatrix(int n) {
- int[][] res = new int[n][n];
- int num = 1;
- // int n2 = Math.pow(n,2);
- int highrow = n-1;
- int highcol = n-1;
- int lowrow = 0;
- int lowcol = 0;
- while(true) {
- if(lowrow>highrow || lowcol > highcol) {
- break;
- }
- if(highrow==lowrow) {
- for(int i=lowcol;i<=highcol;i++) {
- res[lowrow][i] = num++;
- }
- break;
- }
- if(highcol == lowcol) {
- for(int i=lowrow;i<=highrow;i++) {
- res[i][lowcol] = num++;
- }
- break;
- }
- for(int i=lowcol;i<=highcol;i++) {
- res[lowrow][i] = num++;
- }
- for(int i=lowrow+1;i<=highrow;i++) {
- res[i][highcol] = num++;
- }
- for(int i=highcol-1;i>=lowcol;i--) {
- res[highrow][i] = num++;
- }
- for(int i=highrow-1;i>=lowrow+1;i--) { //注意最后一个边界
- res[i][lowcol] = num++;
- }
- highrow--;
- highcol--;
- lowrow++;
- lowcol++;
- }
- return res;
- }

浙公网安备 33010602011771号