Thursday, July 17, 2014

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
螺旋数组,其实就是找出数学规律。
public class Solution {
    //Time: O(n^2)  Space: O(n^2)
    public int[][] generateMatrix(int n) {
        int count = 0;
        int[][] matrix = new int[n][n];
        generate(matrix, n, count, 0);
        return matrix;
    }
    
    private void generate(int[][] matrix, int size, int count, int offset) {
        if (count == matrix.length * matrix.length) {
            return;
        }
        
        for (int i = 0; i < size; i++) {
            matrix[offset][offset + i] = ++count;
        }
        for (int i = 1; i < size; i++) {
            matrix[offset + i][offset + size - 1] = ++count;
        }
        for (int i = size - 2; i >= 0; i--) {
            matrix[offset + size - 1][offset + i] = ++count;
        }
        for (int i = size - 2; i > 0; i--) {
            matrix[offset + i][offset] = ++count;
        } 
        generate(matrix, size - 2, count, offset + 1);
    }
}

No comments:

Post a Comment