enter image description hereI am getting a runtime error for the rat in the maze problem. Could you pls tell me where I am going wrong?
Problem:
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), and 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and the rat cannot move to it while value 1 at a cell in the matrix represents that the rat can be travel through it. Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.
Code:
class Solution:
def findPath(self, m, n):
# code here
if m[0][0]==0 or m[n-1][n-1]==0:
return []
list_of_ans=[]
vis=[]
ans=''
vis=[[0 for _ in range(n)]for _ in range(n)]
list_of_ans=self.search(n,m,ans,0,0,list_of_ans,vis)
list_of_ans.sort()
return list_of_ans
def search(self,n,m,ans,i,j,list_of_ans,vis):
if i==n-1 and j==n-1:
list_of_ans.append(ans)
return list_of_ans
if vis[i][j 1]==0 and j 1<n and m[i][j 1]==1:
vis[i][j 1]=1
ans = 'R'
list_of_ans=self.search(n,m,ans,i,j 1,list_of_ans,vis)
vis[i][j 1]=0
if vis[i-1][j]==0 and i-1>-1 and m[i-1][j]==1:
vis[i-1][j]=1
ans ='U'
list_of_ans=self.search(n,m,ans,i-1,j,list_of_ans,vis)
vis[i-1][j]=0
if vis[i][j-1]==0 and j-1>-1 and m[i][j-1]==1:
vis[i][j-1]=1
ans ='L'
list_of_ans=self.search(n,m,ans,i,j-1,list_of_ans,vis)
vis[i][j-1]=0
if vis[i 1][j]==0 and i 1<n and m[i 1][j]==1:
vis[i 1][j]=1
ans ='D'
list_of_ans=self.search(n,m,ans,i 1,j,list_of_ans,vis)
vis[i 1][j]=0
return list_of_ans
Input:
N = 4
m[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 1, 1, 1}}
Error:
Traceback (most recent call last):
File "/home/e06cd8a4132efe0b88133e02abde22fd.py", line 70, in <module>
result = ob.findPath(matrix, n[0])
File "/home/e06cd8a4132efe0b88133e02abde22fd.py", line 12, in findPath
list_of_ans=self.search(n,m,ans,0,0,list_of_ans,vis)
File "/home/e06cd8a4132efe0b88133e02abde22fd.py", line 47, in search
list_of_ans=self.search(n,m,ans,i 1,j,list_of_ans,vis)
File "/home/e06cd8a4132efe0b88133e02abde22fd.py", line 26, in search
list_of_ans=self.s.................
CodePudding user response:
if vis[i][j 1]==0 and j 1<n and m[i][j 1]==1:
This might cause an error because it evaluates vis[i][j 1]==0
before checking j 1<n
. So if j
ever equals n
, the first check will cause an error before checking of j 1
if valid.
To fix this, just change the order of your conditions. You need to make similar changes to all of your if
statements.