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

[leetcode] Spiral Matrix II

时间:2014-06-27 11:40:49      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:class   code   java   http   tar   com   

 

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

https://oj.leetcode.com/problems/spiral-matrix-ii/

思路:按要求输出,注意边界。

public class Solution {
	public int[][] generateMatrix(int n) {
		int[][] mat = new int[n][n];
		if (n <= 0)
			return mat;
		int num = 1;
		int left = 0;
		int right = n - 1;
		int top = 0;
		int bottom = n - 1;
		while (num <= n * n) {
			int i;
			for (i = left; i <= right; i++)
				mat[top][i] = num++;

			for (i = top + 1; i <= bottom; i++)
				mat[i][right] = num++;

			if (top < bottom)
				for (i = right - 1; i >= left; i--)
					mat[bottom][i] = num++;

			if (left < right)
				for (i = bottom - 1; i >= top + 1; i--)
					mat[i][left] = num++;
			top++;
			left++;
			bottom--;
			right--;

		}

		return mat;
	}

	public static void main(String[] args) {
		System.out.println(new Solution().generateMatrix(1));
	}

}

 

 

 

 

[leetcode] Spiral Matrix II,布布扣,bubuko.com

[leetcode] Spiral Matrix II

标签:class   code   java   http   tar   com   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810778.html

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