I am given a square grid
0 0 0 0 0 0
1 0 0 1 1 1
1 1 0 0 0 0
1 1 1 1 1 0
1 1 1 1 0 0
1 1 1 1 1 0
I can traverse the grid by only moving up, down, left, right but not diagonally. I need to find the maximum y-coordinate of the path with a length of at most 10 units. y-coordinate increases as we move downwards vertically.
In this example, it would be 6, as we can reach the bottom right of the grid.
- I also need to know the path of the way to get there.
- If there are multiple paths that are optimal, I can print any one of them.
- I can also start and end anywhere I choose on the top row(
0 0 0 0 0 0
in this case) - I cannot go on a square that contains a 1, I can only go on squares that contain a 0.
I have read this grid into a 2d list. I have attempted to solve this with a modified dfs, however, it loops forever and does not give an answer.
def dfa(curr_X,curry,steps_taken,a,distance_from_start,path_taken=[0]):
if(not path_taken):
path_taken=[0]
if steps_taken>28:
return path_taken
else:
if a[curry+1][curr_X]!=1:
if(not path_taken):
path_taken=[0]
path_taken[0]=path_taken[0]+1
path_taken.append("01")
return dfa(curr_X,curry+1,steps_taken+1,a,distance_from_start+1,path_taken)
else:
if a[curry][curr_X+1]!=1 and a[curry][curr_X-1]!=1:
if(not path_taken):
path_taken=[0]
path_taken_right=path_taken.append("11")
path_taken_left=path_taken.append("10")
if(not path_taken):
path_taken=[0]
right_path=dfa(curr_X+1,curry,steps_taken+1,a,distance_from_start,path_taken_right)
if(not path_taken):
path_taken=[0]
left_path=dfa(curr_X-1,curry,steps_taken+1,a,distance_from_start,path_taken_left)
temp_max=max(right_path[0],left_path[0])
if(temp_max==right_path[0]):
return dfa(curr_X+1,curry,steps_taken+1,a,distance_from_start,path_taken_right)
else:
return dfa(curr_X-1,curry,steps_taken+1,a,distance_from_start,path_taken_left)
elif a[curry][curr_X+1]!=1:
path_taken.append("11")
return dfa(curr_X+1,curry,steps_taken+1,a,distance_from_start,path_taken)
elif a[curry][curr_X-1]!=1:
path_taken.append("10")
return dfa(curr_X+1,curry,steps_taken+1,a,distance_from_start,path_taken)
else:
path_taken.append("00")
path_taken[0]=path_taken[0]-1
return dfa(curr_X,curry-1,steps_taken+1,a,distance_from_start-1,path_taken)
else:
path_taken.append("00")
path_taken[0]=path_taken[0]-1
return dfa(curr_X,curry-1,steps_taken+1,airspace,distance_from_start-1,path_taken)
Stepping through the program with a debugger does not give me a definitive answer as to why it loops forever. Sorry for the long code, I cannot shorten it as I need to cover edge cases where the optimal path starts at the bottom left or bottom right. I am sure that this problem requires some dfs, however, if it does not require dfs, I am open to seeing a better method.
BFS could also be a option.