<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>> res(n,vector<int>(n,-1));
        int count = 1;
        int dir_idx = 0;
        int x = 0,y =0;
        while(count <= n*n){
            res[x][y] = count;
            int new_x = x+dirs[dir_idx][0];
            int new_y = y+dirs[dir_idx][1];
            if(new_x >= n || new_x<0 || new_y >=n || new_y<0 || res[new_x][new_y]!= -1){
                dir_idx = (dir_idx+1) %4;
                new_x = x+dirs[dir_idx][0];
                new_y = y+dirs[dir_idx][1];
            }
            count++;
            x = new_x;
            y = new_y;
        }
        return res;
    }
private:
    vector<vector<int>> dirs = {{0,1},{1,0},{0,-1},{-1,0}};
};
7800