首页 > 其他 > 详细

[LeetCode 59] Spiral Matrix II

时间:2015-03-23 09:34:41      阅读:187      评论:0      收藏:0      [点我收藏+]

题目链接: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 ]
		]
 *
 */

public class SpiralMatrixII {

	
//	21 / 21 test cases passed.
//	Status: Accepted
//	Runtime: 208 ms
//	Submitted: 0 minutes ago

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        
        //			up
        // left				right
        //			down
        
        int left = 0;
        int right = n - 1;
        int up = 0;
        int down = n - 1;
        int count = 0;
        while(left <= right && up <= down) {
        	
        	for(int i = left; i <= right; i ++) {
        		matrix[up][i] = (++ count);
        	}
        	up ++;
        	
        	for(int i = up; i <= down; i ++) {
        		matrix[i][right] = (++count);
        	}
        	right --;
        	
        	for(int i = right; i >= left && up <= down; i --) {
        		matrix[down][i] = (++count);
        	}
        	down --;
        	
        	for(int i = down; i >= up && left <= right; i --) {
        		matrix[i][left] = (++ count);
        	}
        	left ++;
        }
        return matrix;
        
    }
	public static void main(String[] args) {
		

	}

}


[LeetCode 59] Spiral Matrix II

原文:http://blog.csdn.net/ever223/article/details/44542825

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!