zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    

      

     
  • 相关阅读:
    C语言I博客作业09
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言II博客作业04
    C语言II博客作业03
    C语言II博客作业02
    C语言|博客作业01
    学期总结
  • 原文地址:https://www.cnblogs.com/flyfatty/p/6646435.html
Copyright © 2011-2022 走看看