【leetcode刷题笔记】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 ]
]

题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的生成矩阵。和第一个的做法类似,定义四个变量

left:当前未填的子矩阵的最左边界

right:当前未填的子矩阵的最右边界

up:当前未填子矩阵的最上边界

down:当前未填子矩阵的最下边界

然后每次进行四个循环,做一个螺旋。

代码如下:

 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] matrix = new int[n][n];
 4         int left  = 0;
 5         int right = n-1;
 6         int up = 0;
 7         int down = n-1;
 8         int number = 0;
 9         while(number <= n*n-1){
10             for(int i = left;i <= right;i++){
11                 matrix[up][i] = number+1;
12                 number++;
13             }
14             up++;
15             
16             for(int i = up;i <= down;i++){
17                 matrix[i][right] = number+1;
18                 number++;
19             }
20             right--;
21             
22             for(int i = right;i >= left;i--){
23                 matrix[down][i] = number+1;
24                 number++;
25             }
26             down--;
27             
28             for(int i = down;i >= up;i--){
29                 matrix[i][left] = number+1;
30                 number++;
31             }
32             left++;
33         }
34         return matrix;
35     }
36 }

 

posted @ 2014-07-07 18:50  SunshineAtNoon  阅读(192)  评论(0编辑  收藏  举报