中级农民
- 积分
- 106
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-2-24
- 最后登录
- 1970-1-1
|
## 1368. Minimum Cost to Make at Least One Valid Path in a Grid
Given a *m* x *n* `grid`. Each cell of the `grid` has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
- **1** which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
- **2** which means go to the cell to the left. (i.e go from `grid[i][j]` to `grid[i][j - 1]`)
- **3** which means go to the lower cell. (i.e go from `grid[i][j]` to `grid[i + 1][j]`)
- **4** which means go to the upper cell. (i.e go from `grid[i][j]` to `grid[i - 1][j]`)
Notice that there could be some **invalid signs** on the cells of the `grid` which points outside the `grid`.
You will initially start at the upper left cell `(0,0)`. A valid path in the grid is a path which starts from the upper left cell `(0,0)` and ends at the bottom-right cell `(m - 1, n - 1)` following the signs on the grid. The valid path **doesn't have to be the shortest**.
You can modify the sign on a cell with `cost = 1`. You can modify the sign on a cell **one time only**.
Return *the minimum cost* to make the grid have at least one valid path.
**Example 1:**

```
Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.
```
**Example 2:**

```
Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).
```
**Example 3:**

```
Input: grid = [[1,2],[4,3]]
Output: 1
```
**Example 4:**
```
Input: grid = [[2,2,2],[2,2,2]]
Output: 3
```
**Example 5:**
```
Input: grid = [[4]]
Output: 0
```
**Constraints:**
- `m == grid.length`
- `n == grid[i].length`
- `1 <= m, n <= 100`
---
### Solution
离AK最近的一次了,哎...因为BFS对于VIS的判断遗漏而导致的超时,有点不甘心。
1. BFS+PriorityQueue
```python
import heapq
from collections import deque
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
d = {1: [0, 1], 2: [0, -1], 3: [1, 0], 4: [-1, 0]}
q = [(0,0,0)]
m = len(grid)
n = len(grid[0])
vis = [[0 for _ in range(n)] for _ in range(m)]
while(q):
cost, i, j = heapq.heappop(q)
if i==m-1 and j==n-1:
return cost
# 就是因为没有加这个vis[i][j]=1超时了!!!还是bfs没有理解透彻啊,哎。。。
if vis[i][j]:
continue
vis[i][j] = 1
for k,v in d.items():
r,c = i+d[k][0],j+d[k][1]
if r<0 or r>=m or c>0 or c>=n or (r,c) or vis[r][c]:
continue
_cost = cost + 1 if grid[i][j]!=k else cost
heapq.heappush(q, (_cost, r, c))
```
|
|