我正在做一个给出网格的问题,例如:
1 1 0 0
0 1 1 0
0 0 1 0
1 0 0 0
n =行数,m =列数。
问题是要找到连接最紧密的链#1;"在网格中...在这种情况下:它是从单元格(0,0)到单元格(2,2)的1-1-1-1-1。
到目前为止,这是我的代码:
def find(x, y):
#uses recursive fill
if x < 0 or y < 0 or matrix[x][y] == -1 or matrix[x][y] == 0 or x>n or y>m:
return 0
else:
return 1 + find(x+1, y) + find(x-1, y) + find(x, y+1) + find(x, y-1)+ find(x+1, y-1)+ find(x-1,y+1) + find(x+1, y+1) + find(x-1, y-1)
matrix = [[0 for a in range(n)] for b in range(m)]
#captures data and puts it in a matrix
for i in range(n):
row = map(int, raw_input().strip().split())
for j in range(m):
matrix[i][j] = row[j]
sums = 0
for i in range(n):
for k in range(m):
if matrix[i][k] == 1:
print matrix[i][k]
sums = max(find(i, k))
print sums
现在,我得到一个&#34;运行时错误&#34;当我运行这个程序但我无法弄清楚原因。我正在进行find
函数的递归填充。其余代码只将raw_input()
中的值存储到矩阵中,如果单元格等于1,则输入find
函数。
编辑:
我得到一个长期重复的错误,看起来像这样(缩短):
Traceback (most recent call last):
File "solution.py", line 27, in <module>
sums = max(find(i, k))
File "solution.py", line 11, in find
return 1 + find(x+1, y) + find(x-1, y) + find(x, y+1) + find(x, y-1)+ find(x+1, y-1)+ find(x-1,y+1) + find(x+1, y+1) + find(x-1, y-1)
File "solution.py", line 11, in find
return 1 + find(x+1, y) + find(x-1, y) + find(x, y+1) + find(x, y-1)+ find(x+1, y-1)+ find(x-1,y+1) + find(x+1, y+1) + find(x-1, y-1)
File "solution.py", line 11, in find
return 1 + find(x+1, y) + find(x-1, y) + find(x, y+1) + find(x, y-1)+ find(x+1, y-1)+ find(x-1,y+1) + find(x+1, y+1) + find(x-1, y-1)
File "solution.py", line 11, in find
return 1 + find(x+1, y) + find(x-1, y) + find(x, y+1) + find(x, y-1)+ find(x+1, y-1)+ find(x-1,y+1) + find(x+1, y+1) + find(x-1, y-1)
File "solution.py", line 11, in find
return 1 + find(x+1, y) + find(x-1, y) + find(x, y+1) + find(x, y-1)+ find(x+1, y-1)+ find(x-1,y+1) + find(x+1, y+1) + find(x-1, y-1)
File "solution.py", line 11, in find
此解决方案可能不是最好的(我是Python的新手),所以任何建议都会受到赞赏。
答案 0 :(得分:1)
您应该在x>n or y>m
之前检查matrix[x][y] == -1 or matrix[x][y] == 0
。否则可能导致out of range
错误。
而且你应该以某种方式标记你的方式,否则你将最终进行无限递归。在您的示例中,您将右转 - >左 - >>右 - >左...并始终找到1
。
答案 1 :(得分:1)
我认为你正在进行无限递归,因为
1
,因此return 1 + find(x+1, y) + ...
1
权利
return 1 + find(x+1, y) + find(x-1, y)
1
(x-1, y
)可能的解决方案:标记“已使用”位置,可能使用2
。