Monday, September 15, 2014

Leetcode: Spiral Matrix II

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 ]
]
Understand the problem:
The problem gives an integer n, generate a square matrix filled in spiral order. 
For example, n = 0, return empty matrix.
For n = 1, return [1]
For n = 2, return [ [1, 2]
                             [4, 3]
                           ]
For n = 3, return the matrix as shown in the problem. 

So the solution would be the very closed to the Spiral matrix I.


Solution:
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        if (n == 0) {
            return result;
        }
         
        int start = 1;
        int row = 0;
        int col = 0;
         
        while (n > 0) {
            if (n == 1) {
                result[row][col] = start;
                break;
            }
             
            // Move right
            for (int i = 0; i < n - 1; i++) {
                result[row][col++] = start++;
            }
             
            // Move down
            for (int i = 0; i < n - 1; i++) {
                result[row++][col] = start++;
            }
             
            // Move left
            for (int i = 0; i < n - 1; i++) {
                result[row][col--] = start++;
            }
             
            // Move up
            for (int i = 0; i < n - 1; i++) {
                result[row--][col] = start++;
            }
             
            row++;
            col++;
            n -= 2;
        }
         
        return result;
    }
}

No comments:

Post a Comment