Saturday, March 7, 2015

59. Spiral Matrix II Leetcode Java

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 ]
]
Solution:
Almost the same as 54. Spiral Matrix
Use a flag to realize spiral order and during the transverse, assign the corresponding values.

  public int[][] generateMatrix(int n) {  
     int[][] res=new int[n][n];  
     if(n==0) return res;  
     int i=1;  
     int top=0;  
     int bottom=n-1;  
     int left=0;  
     int right=n-1;  
     int flag=0;  
     while(i<=n*n){  
       switch(flag){  
         case 0: for(int j=left;j<=right;j++) res[top][j]=i++;  
             flag=1;  
             top++;  
             break;  
         case 1: for(int j=top;j<=bottom;j++) res[j][right]=i++;  
             flag=2;  
             right--;  
             break;  
         case 2: for(int j=right;j>=left;j--) res[bottom][j]=i++;  
             flag=3;  
             bottom--;  
             break;  
         case 3: for(int j=bottom;j>=top;j--) res[j][left]=i++;  
             flag=0;  
             left++;  
             break;  
         default : break;  
       }  
     }  
     return res;  
   }  

No comments:

Post a Comment