[leetcode]Spiral Matrix II

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 ]
]

算法思路:

在n*n矩阵中,循环打印1 ~ n^2数字,一圈一圈处理即可,很容易

【注意】:当n为奇数时,最中间的一个数字的处理,我的解法,当n为奇数时,最中间的数字是无法打印的,因此需要特殊处理。

代码如下:

 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         if(n <= 0) return new int[0][0];
 4         int[][] res = new int[n][n];
 5         int index = 1;
 6         for(int i = 0; i < n >> 1; i++){
 7             for(int j = i ; j < n - i; j++){
 8                 res[i][j] = index++;
 9             }
10             for(int j = i + 1; j < n - i; j++){
11                 res[j][n - 1 - i] = index++;
12             }
13             for(int j = n - i - 2; j >= i; j--){
14                 res[n - 1 - i][j] = index++;
15             }
16             for(int j = n - i - 2; j > i; j-- ){
17                 res[j][i] = index++;
18             }
19         }
20         if(n % 2 == 1) res[n >> 1][n >> 1] = index;
21         return res;
22     }
23 }

 




 

posted on 2014-08-15 14:54  喵星人与汪星人  阅读(283)  评论(0编辑  收藏  举报