重温 dijkstra算法(2)
继上一篇
https://blog.csdn.net/weixin_43146899/article/details/123166708?spm=1001.2014.3001.5501
1514. 概率最大的路径
目标是求 start 到end 的最大概率路径的概率值, 求最大,同样使用优先队列,加入队列之前权重取一个负值,
首先构建节点的邻接表,方便拓展节点时对其邻居快速访问
队列一开始就 起点以及在队列中,每次对于出队 的节点访问其邻居 并且比较之前到其邻居的概率和通过该节点到其邻居的概率 ,大的保留,并且将其入队,
最后若出队元素为 end 返回权重,否则返回0
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
tgl = [[] for _ in range(n)]
for i in range(len(succProb)):
x,y,w = edges[i][0],edges[i][1],succProb[i]
tgl[x].append((y,w))
tgl[y].append((x,w))
vis = [0] *n
dis = [0] *n
dis[start] =1
heap =[(0,start)]
while heap:
wht,node = heapq.heappop(heap)
if node ==end:
return -wht
if vis[node] == 0:
for ano,tiw in tgl[node]:
if dis[node]*tiw >dis[ano]:
dis[ano] = dis[node]*tiw
heapq.heappush(heap,(-dis[ano],ano))
vis[node]=1
return dis[end]
1368. 使网格图至少有一条有效路径的最小代价
二维 dijkstra
由于更新每次权重值+1或者不加, 所以通过dijkstra方法 先访问的点权重值一定小于后访问的点,一开始队列中就只有 (0,0)点 , 对于所有出队元素 对其邻居进行访问,且方向相同的邻居权重值不变,
直到出队元素为最右下角的点
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m ,n = len(grid),len(grid[0])
dis = [[m+n-2]*n for _ in range(m)]
vis = [[0]*n for _ in range(m)]
ner = [(0,1),(0,-1),(1,0),(-1,0)]
heap = [(0,0,0)]
while heap :
w,x,y = heapq.heappop(heap)
if x==m-1 and y ==n-1:
return w
if vis[x][y] ==0:
for k in range(4):
nex ,ney = x+ner[k][0],y+ner[k][1]
if 0<=nex<m and 0<=ney<n and vis[nex][ney] == 0:
neww =w+1
if grid[x][y] ==k+1:
neww =w
# print("push:",nex,ney,neww)
if neww <dis[nex][ney]:
dis[nex][ney] =neww
heapq.heappush(heap,(neww,nex,ney))
vis[x][y] = 1
return dis[m-1][n-1]