Inverse Spiral Matrix

Given a matrix, return a list that represents the spiraling out of the matrix starting from the center of the matrix.

The Idea: Reverse a list of size n*m. Starting from the center of the matrix is equivalent to starting on the top right, and spiraling inwards. Append the elements backwards in a reserved list.

Complexity: O(n*m) time and O(1) space, although we are modifying the contents of the matrix.

import sys


def mid_spiral_traversal(matrix):
    move = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    spiral = [0] * len(matrix) * len(matrix[0])
    bk_iter = len(spiral) - 1

    rotation = 0
    r = 0
    c = 0
    stop_r = 2 * min(len(matrix), len(matrix[0])) + 1
    cur_mov = move[rotation % len(move)]

    while rotation < stop_r:
        # each rotation is a new direction
        while 0 <= r < len(matrix) and 0 <= c < len(matrix[0]) \
                and matrix[r][c] != sys.maxsize:
            spiral[bk_iter] = matrix[r][c]
            matrix[r][c] = sys.maxsize
            r += cur_mov[0]
            c += cur_mov[1]
            bk_iter -= 1

        # we overcounted by 1
        r -= cur_mov[0]
        c -= cur_mov[1]

        # begin the next direction
        rotation += 1
        cur_mov = move[rotation % len(move)]
        r += cur_mov[0]
        c += cur_mov[1]

    return spiral


t1 = [[1, 2, 3 ],
      [4, 5, 6],
      [7, 8, 9]]
t2 = [[ 1,  2,  3,  4,  5,  6 ],
      [ 14, 15, 16, 17, 18, 7 ],
      [ 13, 12, 11, 10, 9,  8 ]]
t3 = [[3],
      [2]]

print(mid_spiral_traversal(t1))
print(mid_spiral_traversal(t2))
print(mid_spiral_traversal(t3))

Last updated