Thursday, November 19, 2015

[leetcode]Spiral Matrix II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
    public int[][] generateMatrix(int n) {
     if (n <= 0) return new int[0][0];
   int matrix[][] = new int[n][n];
   int start = 0;
   int end = n-1;
   int current = 1;
   while (start < end){
    for (int i = start; i < end; i++){
     matrix[start][i] = current++;
    }
    for (int i = start; i < end; i++){
     matrix[i][end] = current++;
    }
    for (int i = end; i > start; i--){
     matrix[end][i] = current++;
    }
    for (int i = end; i > start; i--){
     matrix[i][start] = current++;
    }
    start++;
    end--;
   }       
   if (n%2 == 1){
    int center = n/2;
    matrix[center][center] = current;
   }
   return matrix;
    }
}

No comments:

Post a Comment