I got this question last week. I did not finish it. Can anyone show some solution code??....so I can learn..Thanks!!!!
Consider an n × n grid. You need to write a function to find a path (not necessarily the shortest path) that it will take to move from cell A to cell B within the grid, and return the path between these cells. A random number is assigned to each grid cell, representing the height of each cell. A move is considered to be a single step from the current position to
some adjacent position in the grid. We can move in all four directions: up (↑), down (↓), left (←), and right (→).
input:
grid1 = [[4,3,5],
[2,3,3],
[2,2,1]
]
output:
[4,3,3,2,1] or [4,2,2,2,1] or [4,3,3,2,2,2,1] or [4,3,3,3,1]
Below is my code, bu the result is not like the output... Please provide your solution here. I would appreciate
## (0,0) is source, (n-1, n-1) is target
import collections
def findPath(grid):
n = len(grid)
seen = set()
dirs = [(-1,0), (1,0), (0,1), (0,-1)]
res = []
queue = collections.deque()
queue.append((0,0))
res.append(grid[0][0])
while queue:
i,j = queue.popleft()
for x,y in dirs:
new_i = x + i
new_j = y + j
if new_i<0 or new_i>=n or new_j<0 or new_j>=n or grid[new_i][new_j] > grid[i][j]:
continue
if (new_i, new_j) in seen:
continue
# print((new_i,new_j))
# print(grid[new_i][new_j])
res.append(grid[new_i][new_j])
if new_i==n-1 and new_j == n-1:
return res
seen.add((new_i, new_j))
queue.append((new_i, new_j))
return None