59. Spiral Matrix II

Description

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

Solution

Iteration, time O(n ^ 2), space O(1)

class Solution {
    public int[][] generateMatrix(int n) {
        if (n < 1) {
            return new int[0][0];
        }
        
        int[][] matrix = new int[n][n];
        int count = 0;
        
        for (int i = 0; i < (n + 1) / 2; ++i) {
            if (i == n - i - 1) {
                matrix[i][i] = ++count; // single item in the center
                break;
            }
            
            for (int j = i; j < n - i - 1; ++j) {
                matrix[i][j] = ++count;
            }
            
            for (int j = i; j < n - i - 1; ++j) {
                matrix[j][n - i - 1] = ++count;
            }
            
            for (int j = n - i - 1; j > i; --j) {
                matrix[n - i - 1][j] = ++count;
            }
            
            for (int j = n - i - 1; j > i; --j) {
                matrix[j][i] = ++count;
            }
        }
        
        return matrix;
    }
}

你可能感兴趣的:(59. Spiral Matrix II)