以递归方式以螺旋顺序打印矩阵

时间:2018-02-07 03:50:01

标签: python algorithm recursion matrix

我找到的所有答案都在提出迭代解决方案。有解决这个问题的递归方法吗?我的尝试看起来非常接近,但还不太正确。

假设我有这个矩阵:

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

我的功能应该打印...

 HELLIFEASTTONIERG

这是我的代码......

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)

它有点螺旋印刷......

HELLIFEASTONGIER

但是不正确。是否有可能以某种方式改变我的功能以获得正确的输出,因为我感觉好像我很接近。或者还有其他递归解决方案吗?

2 个答案:

答案 0 :(得分:1)

这是一个递归解决方案,逐层解决,从最外层开始,顺时针方向:

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)

答案 1 :(得分:0)

简单干净地做螺旋形(Python 3 +)

def spiralOrder(matrix):
        return matrix and [*matrix.pop(0)] + spiralOrder([*zip(*matrix)][::-1])

ab = [
    ["H", "E", "L", "L"], 
    ["N", "I", "E", "I"], 
    ["O", "G", "R", "F"], 
    ["T", "S", "A", "E"]
    ]
print(''.join(spiralOrder(ab)))