智能驾驶 (200)
- 一辆汽车从m * n的地图的左上角开往右下角,经过每一个地点都需要消耗一定的油量,加油站可以加满油;
- 可以上下左右四个方向行走;
- 地图数字为0表示不可通行,-1表示加油站(可加满为100),正整数表示经过该点消耗的油量;
- 计算从起点到达终点所需的最少初始油量,无法到达右下角则输出-1;
输入描述:
地图大小m n,均在【0, 200】
后续m行,表示地图数字
输出描述:
可以到达终点的最少的初始油量;无法达到输出-1
示例1
输入:
2 2
10 20
30 40
输出:
70
示例2
输入:
4 4
10 30 30 20
30 30 -1 10
0 20 20 40
10 -1 30 40
输出:
70
示例3
输入:
4 4
10 30 30 20
30 30 20 10
10 20 10 40
10 20 30 40
输出:
-1
思路:
- 二分法,获取一个初始的油量;
- BFS,判断该初始的油量能否到达终点;
#
row, col = list(map(int, input().strip().split()))
matrix = []
# 控制不重复行走
visited = [[0 for _ in range(col)] for _ in range(row)]
# 四个方向
directs = [0, 1, 0, -1, 0]
for i in range(row):
matrix.append(list(map(int, input().strip().split())))
# 广度优先
def bfs(mid) :
if matrix[0][0] == -1:
left_oil = 100
elif matrix[0][0] == 0:
return 0
elif matrix[0][0] > mid:
return 0
else:
left_oil = mid - matrix[0][0]
# 广度优先,入队
queue = []
queue.append([0, 0, left_oil])
while queue:
x, y, cur_oil = queue.pop(0)
visited[x][y] = 1
# 走四个方向
for d in range(4):
xx = x + directs[d]
yy = y + directs[d+1]
if xx >= 0 and xx < row and yy >= 0 and yy < col \
and matrix[xx][yy] != 0 and visited[xx][yy] == 0 \
and matrix[xx][yy] <= cur_oil:
if matrix[xx][yy] != -1:
next_oil = cur_oil - matrix[xx][yy]
else:
next_oil = 100
queue.append([xx, yy, next_oil])
return visited[row - 1][col - 1]
# 二分法 获取一个油量
left = 0
right = 100
result = -1
while left <= right:
# 恢复visited
for i in range(row):
for j in range(col):
visited[i][j] = 0
#
mid = (left + right) // 2
if bfs(mid) == 1:
result = mid
right = mid - 1
else:
left = mid + 1
print(result)