Skip to content

2D Array Traversal

Rotate Image (Leetcode 48)

class Solution:
    def reverse(self, arr):
        i, j = 0, len(arr) - 1
        while j > i:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
            j -= 1

    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        H, W = len(matrix), len(matrix[0])
        for i in range(H):
            for j in range(i, W):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 


        for row in matrix:
            self.reverse(row)

Spiral Matrix (Leetcode 54)

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        m, n = len(matrix), len(matrix[0])
        up, down = 0, m - 1
        left, right = 0, n - 1

        out = []

        while len(out) < m * n:
            if up <= down:
                for i in range (left, right + 1):
                    out.append(matrix[up][i])

                up += 1

            if left <= right:
                for i in range(up, down + 1):
                    out.append(matrix[i][right])

                right -= 1

            if down >= up:
                for i in range(right, left - 1, -1):
                    out.append(matrix[down][i])

                down -= 1

            if right >= left:
                for i in range(down, up - 1, -1):
                    out.append(matrix[i][left])

                left += 1

        return out