> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/array_and_numbers/spiral-matrix/spiral-matrix-ii.md).

# 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).
