Leetcode-Spiral Matrix II

LiBlog發表於2014-11-17

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 ]
]
Have you met this question in a real interview?
 
Solution:
 1 public class Solution {
 2     public int[][] generateMatrix(int n) {
 3         int[][] matrix = new int[n][n];
 4 
 5         int[] x = new int[]{0,1,0,-1};
 6         int[] y = new int[]{1,0,-1,0};      
 7         int direction = 0;
 8         int curX = 0, curY=0;        
 9         int rowStart = 0, rowEnd = n-1, colStart=0, colEnd=n-1;
10         int len = n*n;
11         
12         for (int i=0;i<len;i++){
13             matrix[curX][curY]=i+1;    
14             int nextX = curX+x[direction];
15             int nextY = curY+y[direction]; 
16             //Determin the availability of next point.
17             if (nextX>rowEnd || nextX<rowStart || nextY>colEnd || nextY<colStart){
18                 direction = (direction+1)%4;
19                 nextX = curX+x[direction];
20                 nextY = curY+y[direction];
21                 //Update the availability of rows and cols according the direction change.
22                 if (direction==1) rowStart++;
23                 if (direction==2) colEnd--;
24                 if (direction==3) rowEnd--;
25                 if (direction==0) colStart++;
26             }
27             curX = nextX;
28             curY = nextY;
29         }
30 
31         return matrix;
32 
33     }
34 }

 

相關文章