<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p>

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

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

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

<ul>
	<li><code>m == matrix.length</code></li>
	<li><code>n == matrix[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 10</code></li>
	<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>
</ul>

class Solution:
    import math
    def sum_is_infinite(self, matrix) -> bool:
        return sum([sum(i) for i in matrix]) == math.inf
    
    def is_valid(self, c, r, m, n, matrix):
        return c < m and c >= 0 and r < n and r>= 0 and matrix[r][c] != math.inf

    def sol1(self, matrix:List[List[int]]) -> List[int]:
        # first we get all the elements of the matrix in order
        # then we populate the matrix
        n = len(matrix)
        m = len(matrix[0])
        all_elements = []
        i = 0
        d = 0
        r = 0
        c = 0
        d_r = [0, 1, 0, -1]
        d_c = [1, 0, -1, 0]
        while len(all_elements) < m*n:
            all_elements.append(matrix[r][c])
            matrix[r][c] = math.inf
            temp_r = d_r[d] + r
            temp_c = d_c[d] + c
            if self.is_valid(temp_c, temp_r, m, n, matrix):
                r = temp_r
                c = temp_c
            else:
                d = (d + 1) % 4
                r = d_r[d] + r
                c = d_c[d] + c
            i += 1
        return all_elements

    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        return self.sol1(matrix)
        
16500