我有一个如下所示的矩阵(取自带参数的txt文件),每个单元格都有邻居。一旦选择一个单元格,该单元格和包含相同数字的所有相邻单元格将消失。

1 0 4 7 6 8
0 5 4 4 5 5
2 1 4 4 4 6
4 1 3 7 4 4

我试着用递归来实现这一点。我把函数分成了四个部分,分别是up()down()left()right()。但我收到一条错误消息:RecursionError: maximum recursion depth exceeded in comparison
cmd=input("Row,column:")
cmdlist=command.split(",")
row,column=int(cmdlist[0]),int(cmdlist[1])
num=lines[row-1][column-1]
def up(x,y):
    if lines[x-2][y-1]==num and x>1:
        left(x,y)
        right(x,y)
        lines[x-2][y-1]=None
def left(x,y):
    if lines[x-1][y-2]==num and y>1:
        up(x,y)
        down(x,y)
        lines[x-1][y-2]=None
def right(x,y):
    if lines[x-1][y]==num and y<len(lines[row-1]):
        up(x,y)
        down(x,y)
        lines[x-1][y]=None
def down(x,y):
    if lines[x][y-1]==num and x<len(lines):
        left(x,y)
        right(x,y)
        lines[x][y-1]=None
up(row,column)
down(row,column)
for i in lines:
    print(str(i).strip("[]").replace(",","").replace("None"," "))

当我给出表示“4”个数的输入(3,3)时,输出必须如下:
1 0   7 6 8
0 5     5 5
2 1       6
4 1 3 7

我不需要固定的代码,只要主要的想法就足够了。谢谢。

最佳答案

递归错误发生在递归未终止时。
您可以不使用索引的set递归来解决此问题:
搜索包含查找到的number的所有索引到all_num_idx
将当前位于(输入)的索引添加到集合tbd(待删除)
tbd上循环并将所有从all_num_idx开始的索引(仅在-1/+1行或列中不同)添加到集合中已存在的任何索引
直到tbd不再增长
删除tbd中的所有索引:

t = """4 0 4 7 6 8
0 5 4 4 5 5
2 1 4 4 4 6
4 1 3 7 4 4"""

data = [k.strip().split() for k in t.splitlines()]

row,column=map(int,input("Row,column:").strip().split(";"))
num = data[row][column]

len_r =len(data)
len_c = len(data[0])

all_num_idx = set((r,c) for r in range(len_r) for c in range(len_c) if data[r][c]==num)

tbd = set( [ (row,column)] ) # inital field
tbd_size = 0                 # different size to enter while
done = set()                 # we processed those already
while len(tbd) != tbd_size:  # loop while growing
    tbd_size=len(tbd)
    for t in tbd:
        if t in done:
            continue
        # only 4-piece neighbourhood +1 or -1 in one direction
        poss_neighbours = set( [(t[0]+1,t[1]), (t[0],t[1]+1),
                                (t[0]-1,t[1]), (t[0],t[1]-1)] )
        # 8-way neighbourhood with diagonals
        # poss_neighbours = set((t[0]+a,t[1]+b) for a in range(-1,2) for b in range(-1,2))
        tbd = tbd.union( poss_neighbours & all_num_idx)
        # reduce all_num_idx by all those that we already addded
        all_num_idx -= tbd
        done.add(t)

# delete the indexes we collected
for r,c in tbd:
    data[r][c]=None

# output
for line in data:
    print(*(c or " " for c in line) , sep=" ")

输出:
Row,column: 3,4

4 0   7 6 8
0 5     5 5
2 1       6
4 1 3 7

这是“洪水填充算法”的一种变体,它只对具有特定值的单元进行洪水填充。见https://en.wikipedia.org/wiki/Flood_fill

08-16 13:50