To solve this problem, we need to find the shortest path (minimum total cost) from the top-left corner to the bottom-right corner of a grid, where each cell has a cost associated with entering it. We can move in four directions: up, down, left, and right.
Approach
The problem can be efficiently solved using Dijkstra's Algorithm because it is designed to find the shortest path in graphs with non-negative weights (here, the cell costs are non-negative). The steps are:
- Initialize a Distance Matrix: This matrix keeps track of the minimum cost to reach each cell from the start. It is initialized to infinity except for the starting cell (top-left corner), which is set to its own cost.
- Priority Queue: Use a min-heap (priority queue) to process cells in order of their current minimum cost. The heap stores tuples of (current cost, row, column).
- Process Cells: For each cell popped from the heap, check if it is the destination. If not, explore its adjacent cells. For each valid adjacent cell, calculate the new cost and update the distance matrix if the new cost is lower than the existing value. Push the new cost and cell coordinates into the heap.
Solution Code
import heapq
def min_path_cost(grid):
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
INF = float('inf')
dist = [[INF for _ in range(cols)] for _ in range(rows)]
dist[0][0] = grid[0][0]
heap = []
heapq.heappush(heap, (grid[0][0], 0, 0))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while heap:
current_cost, r, c = heapq.heappop(heap)
# If we reach the destination, return the cost
if r == rows - 1 and c == cols - 1:
return current_cost
# Skip if a better path to this cell already exists
if current_cost > dist[r][c]:
continue
# Explore all four directions
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
new_cost = current_cost + grid[nr][nc]
if new_cost < dist[nr][nc]:
dist[nr][nc] = new_cost
heapq.heappush(heap, (new_cost, nr, nc))
# If no path exists (though grid is fully accessible in most cases)
return -1
# Example usage:
grid = [[1,3,1],[1,5,1],[4,2,1]]
print(min_path_cost(grid)) # Output: 7
Explanation
- Distance Matrix: The matrix
distensures we always have the minimum cost to reach each cell. This avoids reprocessing cells with higher costs. - Priority Queue: The min-heap ensures we always process the cell with the current lowest cost first, which is key to Dijkstra's algorithm.
- Adjacent Cells: For each cell, we check all four directions. If moving to an adjacent cell results in a lower cost, we update the distance and push the new state into the heap.
This approach efficiently finds the minimum cost path with a time complexity of O(rows cols log(rows cols)) due to the heap operations, which is optimal for this problem. The space complexity is O(rows cols) for the distance matrix and the heap.
Answer: The code above returns the minimum path cost from the top-left to the bottom-right corner of the grid. For the example grid, the output is 7. For your specific grid, replace the example grid with your input to get the result. If you provide the grid values, I can compute the exact answer. However, based on the problem description, the code is the solution.
If we assume the user expects the code as the answer, then the final answer is the code provided. But if the user had a specific grid, let's say the example given, the answer is 7. Since the user didn't provide the grid, the code is the correct solution.
But according to the problem statement, the user needs to solve the problem, so the code is the solution.
Final Answer: The code as above, or if a specific grid is given, the numerical result. For the example grid, it's 7. So if the user's grid is the example, the answer is 7. \boxed{7}


作者声明:本文包含人工智能生成内容。