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:
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