Traverse a matrix in spiral form

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if matrix == []:
            return matrix
        if len(matrix) == 1:
            return matrix[0]
        
        out = []
        length = len(matrix) - 1

        we = 0
        ns = 1
        ew = 1
        sn = 1

        while len(out) <= (len(matrix[0]) * len(matrix)):
            if len(out) == (len(matrix[0]) * len(matrix)):
                break
            for x in range(we, len(matrix[0]) - we):
                if len(out) == (len(matrix[0]) * len(matrix)):
                    break
                print("East to west", matrix[we][x])
                out.append(matrix[we][x])
            we += 1

            for j in range(ns, (length - ns) + 2):
                if len(out) == (len(matrix[0]) * len(matrix)):
                    break
                print( j, len(matrix[0]) - ns)
                print("North to south", matrix[j][len(matrix[0]) - ns])
                out.append(matrix[j][len(matrix[0]) - ns])
            ns += 1

            for x in range(ew, len(matrix[0]) - ew + 1):
                if len(out) == (len(matrix[0]) * len(matrix)):
                    break
                print("West to east", matrix[length - ew + 1][len(matrix[0]) - 1 - x])
                out.append(matrix[length - ew + 1][len(matrix[0]) - 1 - x])
            ew += 1

            for x in range(sn, len(matrix) - sn):
                if len(out) == (len(matrix[0]) * len(matrix)):
                    break
                print("South to North", matrix[x][sn - 1])
                out.append(matrix[len(matrix) - x - 1][sn - 1])
            sn += 1

        print(out)
        return out

© 2021 Tecnance • by Juan Suarez