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

leetcode--Spiral Matrix II

时间:2014-06-18 21:56:47      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   for   leetcode   

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 class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
		if(n > 0){
			int num = 1;
			for(int i = 0; i < n / 2; ++i){
				for(int k = i; k < n - i; ++k){
					result[i][k] = num;
					++num;
				}
				for(int k = i + 1; k < n - (i + 1); ++k){
					result[k][n - (i + 1)] = num;
					++num;
				}
				for(int k = i; k < n - i; ++k){
					result[n - 1 - i][n - 1 - k] = num; 
					++num;
				}
				for(int k = i + 1; k < n - (i + 1); ++k){
					result[n - 1 - k][i] = num;
					++num;
				}
			}
			if(n % 2 != 0)
				result[n / 2][n / 2] = num;
		}
		return result;    
    }
}

  

leetcode--Spiral Matrix II,布布扣,bubuko.com

leetcode--Spiral Matrix II

标签:class   blog   code   java   for   leetcode   

原文地址:http://www.cnblogs.com/averillzheng/p/3790270.html

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