This is a code for finding shortest path through a rectangular (can be square too) maze in which movements in all four directions are allowed and the rat can skip or break one wall. I have used recursion and backtracking below. Out of 5 test cases it is passes 3 of then and wrong answere in the rest. Can any one help me in finding out the mistake...??
def is_safe(m,i,j,a,v):
if(v[i][j]==False ):
if(m[i][j]==0):
return True
elif(m[i][j]==1 and a[0]==0):
a[0]+=1
return True
elif(m[i][j]==1 and a[0]==1):
a[0]+=1
return False
else:
return False
else:
return False
def solution(m):
h=len(m)
w=len(m[0])
print(h,w)
v=[]
for x in range(h):
a=[]
for y in range(w):
a.append(False)
v.append(a)
li=[]
c=0
p=1
i=0
j=0
path_finder(m,i,j,h,w,li,p,c,v)
return min(li)
def path_finder(m,i,j,h,w,li,p,c,v):
if(c==2):
return
if(i==h-1 and j==w-1):
li.append(p)
return
a1=[c]
a2=[c]
a3=[c]
a4=[c]
v[i][j]=True
if(i+1<h and is_safe(m,i+1,j,a1,v)):
path_finder(m,i+1,j,h,w,li,p+1,a1[0],v)
if(i-1>=0 and is_safe(m,i-1,j,a2,v)):
path_finder(m,i-1,j,h,w,li,p+1,a2[0],v)
if(j+1<w and is_safe(m,i,j+1,a3,v)):
path_finder(m,i,j+1,h,w,li,p+1,a3[0],v)
if(j-1>=0 and is_safe(m,i,j-1,a4,v)):
path_finder(m,i,j-1,h,w,li,p+1,a4[0],v)
v[i][j]=False