59. Spiral Matrix II【数组】

2017/3/30 14:28:32


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 ]
]
 
版本1:该题是螺旋矩阵问题的逆过程,对原问题稍作修改即可。
public class Solution {
    public int[][] generateMatrix(int n) {
        List<Integer> list = new ArrayList<Integer>();
		int count = 0;
		int[][] matrix = new int[n][n];
		if( n == 0 ) return matrix;
		int Gu_1 = n , Gu_2 = n , Gu_3 = -1;//外围哨兵
		int i = 0 , j = -1 , flag = 1;
		while( count < n*n ){
			switch( flag % 4 ){
				case 1: 
					if (j+1 == Gu_1 || matrix[i][j+1]!=0 )
						flag++;
					else{
						count++;
						matrix[i][++j] = count;
					}
					break;
				case 2: 
					if (i+1 == Gu_2 || matrix[i+1][j]!=0 )
						flag++;
					else{
						count++;
						matrix[++i][j] = count;
					}
					break;
				case 3:
					if (j-1 == Gu_3 || matrix[i][j-1]!=0)
						flag++;
					else{
						count++;
						matrix[i][--j] = count;
					}
					break;
				case 0: 
					if (matrix[i-1][j]!=0)
						flag++;
					else{
						count++;
						matrix[--i][j] = count;
					}
					break;
			}
		}
        return matrix;
    }
}

  

 
posted @ 2017-03-30 15:28  会飞的胖子  阅读(97)  评论(0编辑  收藏  举报