Spiral Matrix II

Description

Given a positive integer n, generate a square matrix filled with elements from 1 to n2n^2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Solution

Idea: fill layer by layer. Suppose n = 4.

Filling the first layer [1,8]. First from left to right: 1,2,3. Then from top to bottom: 4,5,6. Then from right to left, 7,8,9. Then from bottom to top: 10,11,12.

Filling the second layer [13,16]. Similar to filling the first layer.

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n, vector<int>(n));
        int i = 1;
        int x = 0, y = 0;
        int k = n - 1;
        for( ; k > 0; k -= 2){
            for(int j = 0; j < k; ++j)
                ans[x][y++] = i++;
            for(int j = 0; j < k; ++j)
                ans[x++][y] = i++;
            for(int j = 0; j < k; ++j)
                ans[x][y--] = i++;
            for(int j = 0; j < k; ++j)
                ans[x--][y] = i++;
            ++x;
            ++y;
        }
        if(k == 0) ans[x][y] = i;
        return ans;
    }
};

Last updated