There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.
Now given all the cities and fights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.
defmaximumMinimumPath(self,A: List[List[int]]) ->int: m, n =len(A),len(A[0]) seen =set() maxHeap = [(-A[0][0],0,0)]heapify(maxHeap)while maxHeap: val, i, j =heappop(maxHeap)if (i, j) == (m-1, n-1):return-val# seen.add((i, j)) 在這裡會TLEfor dy, dx in ((0,1), (1,0), (0,-1), (-1,0)): y = i + dy x = j + dxifnot (0<= y < m and0<= x < n and (y, x) notin seen):continue# 這邊是要比較cur and new 哪個比較小heappush(maxHeap, (max(val, -A[y][x]), y, x)) seen.add((y ,x))# 在這會pass# if A has only 1 elementreturn A[0][0]
778. Swim in Rising Water
Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]Output:16Explanation:0123424232221512131415161117181920109876The final route is marked in bold.We need to wait until time 16 so that (0, 0)and (4,4) are connected.
"""Dijkstra: 每次尋找regional min並且紀錄路線中出現的max"""from heapq import*classSolution:defswimInWater(self,grid: List[List[int]]) ->int: n =len(grid) heap = [(grid[0][0],0,0)] max_t =0 seen =set()while heap: val, i, j =heappop(heap) max_t =max(max_t, val)if (i, j) == (n-1, n-1):return max_tfor dy, dx in ((0,1), (1,0), (0,-1), (-1,0)): y = i + dy x = j + dxifnot(0<=y<n and0<=x<n and (y,x) notin seen):continueheappush(heap, (grid[y][x], y, x)) seen.add((y, x))