Spiral Matrix II

https://leetcode.com/problems/spiral-matrix-ii/description/

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Thoughts

和I一个思路, 只是在遍历时顺便放值.

Code

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n));
        int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1, count = 1;
        while (rowBegin <= rowEnd && colBegin <= colEnd) {
            for (int i = colBegin; i <= colEnd; ++i) {
                res[rowBegin][i] = count++;
            }
            ++rowBegin;

            for (int i = rowBegin; i <= rowEnd; ++i) {
                res[i][colEnd] = count++;
            }
            --colEnd;

            for (int i = colEnd; i >= colBegin; --i) {
                res[rowEnd][i] = count++;
            }
            --rowEnd;

            for (int i = rowEnd; i >= rowBegin; --i) {
                res[i][colBegin] = count++;
            }
            ++colBegin;
        }

        return res;
    }
};

Analysis

时空复杂度O(MN).

Last updated