59. Spiral Matrix II

跟spiral matrix类似

 

 1 class Solution {
 2     public int[][] generateMatrix(int n) {
 3         if(n == 0) return null;
 4         int[][] res = new int[n][n];
 5         int top = 0;
 6         int right = n-1;
 7         int bottom = n-1;
 8         int left = 0;
 9         int num = 1;
10         while(num <= n*n) {
11             for(int i = left; i <= right; i++) {
12                 res[top][i] = num;
13                 num++;
14             }
15             if(num > n*n) break;
16             top++;
17             
18             for(int i = top; i <= bottom; i++) {
19                 res[i][right] = num;
20                 num++;
21             }
22             if(num > n*n) break;
23             right--;
24             
25             for(int i = right; i >= left; i--) {
26                 res[bottom][i] = num;
27                 num++;
28             }
29             if(num > n*n) break;
30             bottom--;
31             
32             for(int i = bottom; i >= top; i--) {
33                 res[i][left] = num;
34                 num++;
35             }
36             if(num > n*n) break;
37             left++;
38             
39             
40         }
41         return res;
42         
43     }
44 }

 

posted @ 2018-09-13 07:23  jasoncool1  阅读(115)  评论(0编辑  收藏  举报