Minimum Path Sum:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Is there any way to print out the path 1 → 3 → 1 → 1 → 1 in Python
I’m having trouble it print out the path instead of the sum. I’m thinking about BFS but my solution doesn’t include the calculation of the weights
def bfs(grid):
queue = collections.deque([[(0,0)]])
seen = set([(0,0)])
while queue:
path = queue.popleft()
x, y = path[-1]
if (x,y) == (width-1, height-1):
return path
for x2, y2 in ((x+1,y), (x-1,y), (x,y+1), (x,y-1)):
if 0 <= x2 < width and 0 <= y2 < height and (x2, y2) not in seen:
queue.append(path + [(x2, y2)])
seen.add((x2, y2))
Linhden is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.