码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Spiral Matrix II

时间:2016-04-06 13:31:14      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

 

Example

Given n = 3,

You should return the following matrix:

[
  [ 1, 2, 3 ],
  [ 8, 9, 4 ],
  [ 7, 6, 5 ]
]


public class Solution {
    /**
     * @param n an integer
     * @return a square matrix
     */
    public int[][] generateMatrix(int n) {
        // Write your code here
        
        if(n == 0)
            return new int[0][0];
        
        int[][] res = new int[n][n];
        int[] num = new int[1];
        num[0] = 1;
        
        for(int i = 0; i < n / 2; i++)
            helper(res, i, num);
        
        if(n % 2 == 1) 
            res[n / 2][n / 2] = num[0];
        
        return res;
    }
    
    public void helper(int[][] res, int layer, int[] num){
        int n = res.length;
        
        int start = layer;
        int end = n - layer - 1;
        
        if(start == end){
            res[start][start] = num[0];
            return;
        }
        
        for(int i = 0; i < end - start; i++){
            res[start][start + i] = num[0];
            num[0] = num[0] + 1;
        }
        for(int i = 0; i < end - start; i++){
            res[start + i][end] = num[0];
            num[0] = num[0] + 1;
        }
        for(int i = 0; i < end - start; i++){
            res[end][end - i] = num[0];
            num[0] = num[0] + 1;
        }
        for(int i = 0; i < end - start; i++){
            res[end - i][start] = num[0];
            num[0] = num[0] + 1;
        }
        
        return;
    }
    
}

 

lintcode-medium-Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5358725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!