<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:
    def generateMatrix(self, n: int) -> List[List[int]]:
        state = 0
        counter = 1
        next_step = [0, 0]

        out = [ [ 0 for _ in range(n) ] for _ in range(n) ]

        while counter <= n ** 2:
            out[next_step[0]][next_step[1]] = counter
            counter += 1

            if state == 0:
                if next_step[1] == (n-1) or out[next_step[0]][next_step[1]+1] != 0:
                    state = 1
                    next_step[0] += 1
                else:
                    next_step[1] += 1
            elif state == 1:
                if next_step[0] == (n-1) or out[next_step[0]+1][next_step[1]] != 0:
                    state = 2
                    next_step[1] -= 1
                else:
                    next_step[0] += 1
            elif state == 2:
                if next_step[1] == 0 or out[next_step[0]][next_step[1]-1] != 0:
                    state = 3
                    next_step[0] -= 1
                else:
                    next_step[1] -= 1
            elif state == 3:
                if out[next_step[0]-1][next_step[1]] != 0:
                    state = 0
                    next_step[1] += 1
                else:
                    next_step[0] -= 1
        
        return out
                





16400