pythonalgorithmrecursionmatrix

print matrix in spiral order recursively


All the answers I find are proposing iterative solutions. Is there a recursive way of solving this problem? I have an attempt that seems quite close but is not quite correct yet.

Suppose I have this matrix:

matrix = [
    ["H", "E", "L", "L"], 
    ["N", "I", "E", "I"], 
    ["O", "G", "R", "F"], 
    ["T", "S", "A", "E"]
    ]

My function should print...

 HELLIFEASTTONIERG

This is my code...

def spiral(matrix, i, j):

    if i < 0  or j < 0 or i >= len(matrix) or j >= len(matrix) or matrix[i][j] == False:
        return False

    print(matrix[i][j])
    matrix[i][j] = False

    if j < len(matrix) and j >= i:
        spiral(matrix, i, j+1)

    if i < len(matrix) and i <= j:
        spiral(matrix, i+1, j)

    if j >= 0 and j <= i:
        spiral(matrix, i , j-1)

    if i >= 0 and i >= j:   
        spiral(matrix, i-1, j)

spiral(matrix, 0, 0)

It prints somewhat spirally...

HELLIFEASTONGIER

but it is incorrect. Is it possible to alter my function somehow to get the right output because I feel as if I'm close. Or is there any other recursive solution?


Solution

  • Here is a recursive solution solving it layer by layer, starts from outermost layer and clockwisely:

    def spiral(matrix, level=0):
        m, n = len(matrix), len(matrix[0])  # MxN matrix
    
        if level >= m // 2 and level >= n // 2:
            return # no more layer to solve
    
        left, right, top, bottom = level, n - 1 - level, level, m - 1 - level
        for j in range(left, right):
            print(matrix[top][j])
    
        for i in range(top, bottom):
            print(matrix[i][right])
    
        for j in range(right, left, -1):
            print(matrix[bottom][j])
    
        for i in range(bottom, top, -1):
            print(matrix[i][left])
    
        spiral(matrix, level=level + 1)