<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 20</code></li>
</ul>

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n, vector<int>(n));
        int first_col = 0;
        int last_col = n - 1;
        int first_row = 0;
        int last_row = n - 1;
        int count = 0;
        int total = n * n;
        while (count < total)
        {
            for (int i = first_col; i <= last_col && count < total; i++)
            {
                ans[first_row][i] = ++count;
            }
            first_row++;
            for (int i = first_row; i <= last_row && count < total; i++)
            {
                ans[i][last_col] = ++count;
            }
            last_col--;
            for (int i = last_col; i >= first_col && count < total; i--)
            {
                ans[last_row][i] = ++count;
            }
            last_row--;
            for (int i = last_row; i >= first_row && count < total; i--)
            {
                ans[i][first_col] = ++count;
            }
            first_col++;
        }
        return ans;
    }
};
7900