[Python] print matrix in spiral order recursively

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    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[j] == False:
    return False

    print(matrix[j])
    matrix[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?

    Continue reading...

Compartilhe esta Página