首页 > 解决方案 > 如何在 Python 中获取二维数组(行主要顺序)中的下一个和上一个值?

问题描述

我正在研究两个函数,它们接收一个二维数组和一个当前行和列值。它应该返回下一个值或上一个值(如果有),如果没有它应该返回 (-1,-1)

在函数中,我将值(数字)称为节点,nodeSolution 是二维数组。

我的问题是,当我使用它回溯时,我的使用功能不断出错。我一直在修复错误,但我似乎无法找到我的代码出错的地方。我得到了很多超出范围的索引,等等。

def nextNode(row, col, nodeSolution):
    if(row == len(nodeSolution) and col == len(nodeSolution)):
        return (-1,-1)
    if(col == len(nodeSolution) - 1):
        return (row+1, 0)
    return (row, col+1)

def previousNode(row, col, nodeSolution):
    if(row == 0 and col == 0):
        return (-1,-1)
    if(col == 0):
        return (row-1, len(nodeSolution) - 1)
    return (row, col-1)

这两个函数都应始终返回二维数组或 (-1,-1) 中的行列值

标签: pythonarraysmultidimensional-array

解决方案


推荐阅读