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;
        }
    }
    

      

     
  • 相关阅读:
    入门OJ 4187【周末舞会】
    入门OJ 1532【排队取款】
    洛谷 P3029 [USACO11NOV]【牛的阵容Cow Lineup】
    洛谷 P1638【逛画展】
    入门OJ 1256【排队】
    PKU 1945【Power Hungry Cows】
    RocketMQ重试机制和消息
    Java操作RocketMQ
    RocketMQ概述
    重定向机制
  • 原文地址:https://www.cnblogs.com/flyfatty/p/6646435.html
Copyright © 2011-2022 走看看