我正在尝试使用3种类型的查询解决以下墙问题(在矩阵上):
1 x y
2 x y
3 x1 y1 x2 y2
如果没有墙,您只能向右或向下移动。
我的编码是这样的:
#Declarations and Assignments
#q = number of above listed queries to execute
rows,cols,q = (int(x) for x in input().split())
mat = [[None]*cols for _ in range(rows)]
class cell:
def __init__(Self):
Self.wr = False #Wall to right
Self.wb = False #Wall at bottom
#safety conition i.e. checking walls
def isSafe(mat,oper,r,c):
if(r>=rows or c>=cols):
return False
elif(oper == 0 and mat[r][c].wr == True):
return False
elif(oper == 1 and mat[r][c].wb == True):
return False
else:
return True
#Recursivepath finder
def path(mat,x1,y1,x2,y2):
#print('path from', x1,y1)
if(x1 == x2 and y1 == y2):
return True
elif(x1 > x2 and y1 > y2):
return False
else:
if(isSafe(mat,0,x1,y1)):
path(mat,x1,y1+1,x2,y2)
if(isSafe(mat,1,x1,y1)):
path(mat,x1+1,y1,x2,y2)
return
#For prining the matrix
def printMat(mat):
for i in range(0,rows):
for j in range(0,cols):
print('For',i,j,':',mat[i][j].wr , ' ', mat[i][j].wb,end="\t")
print('\n')
#Forming Matrix
for i in range(0,rows):
for j in range(0,cols):
mat[i][j] = cell()
#Taking the q queries
for i in range(0,q):
t = [int(i) for i in input().split()]
if(t[0] == 1):
mat[t[1]][t[2]].wr = True
elif(t[0] == 2):
mat[t[1]][t[2]].wb = True
elif(t[0] == 3):
#print('Path from', t[1],t[2],'to',t[3],t[4])
if(path(mat,t[1],t[2],t[3],t[4])):
print(1)
else: print(0)
让样本输入为:
4 5 7 #(一个4x5矩阵和7个查询)
2 1 0
1 1 1
1 2 1
2 2 0
2 2 1
1 0 1
3 0 0 2 1
执行时,我可以看到我已经从0,0到达了2,1。此外,该函数查找可能的所有路径为2,1但最终结果始终打印为0而不是1.这意味着path()(尽管到达目标节点并找到所有可能的路径)不会返回true。这可能是在递归问题中返回的。有人可以解决这个问题并解释递归语句吗?