您的位置:首页 > 其它

[LeetCode 59] Spiral Matrix II

2015-03-22 21:57 369 查看
题目链接: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

;
        
        //			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) {
		

	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: