Thursday, January 8, 2015

LeetCode 59: 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 ]
]
public class Solution {
    public int[][] generateMatrix(int n) {
        // Separately calculate four sides of matrix
        int[][] result = new int[n][n];
        
        int left = 0, right = n-1, top = 0, bottom = n-1;
        int num = 1;
        
        while (left<right && top<bottom)
        {
            for (int i = left; i < right; i++)
                result[top][i] = num++;
                
            for (int i = top; i < bottom; i++)
                result[i][right] = num++;
                
            for (int i = right; i > left; i--)
                result[bottom][i] = num++;
                
            for (int i = bottom; i > top; i--)
                result[i][left] = num++;
                
            left++;
            right--;
            top++;
            bottom--;
        }
        
        // If n is odd number, fill the center.
        if (n%2 == 1)
            result[n/2][n/2] = num;
            
        return result;
    }
}

No comments:

Post a Comment