GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/python/743_Network_Delay_Time.py at master · qiyuangong/leetcode Expand file tree/ Copy path743_Network_Delay_Time.pyMore file actions 44 lines (36 loc) · 1.37 KB / Copy path743_Network_Delay_Time.pyFile metadata and controls44 lines (36 loc) · 1.37 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class Solution(object): # def networkDelayTime(self, times, N, K): # # DFS # graph = collections.defaultdict(list) # for u, v, w in times: # graph[u].append((w, v)) # dist = {node: float('inf') for node in xrange(1, N + 1)} # def dfs(node, elapsed): # if elapsed >= dist[node]: return # dist[node] = elapsed # for time, nei in sorted(graph[node]): # dfs(nei, elapsed + time) # dfs(K, 0) # ans = max(dist.values()) # return ans if ans < float('inf') else -1 def networkDelayTime(self, times, N, K): # Dijkstra graph = collections.defaultdict(list) for u, v, w in times: graph[u].append((v, w)) dist = {node: float('inf') for node in xrange(1, N + 1)} seen = [False] * (N + 1) dist[K] = 0 while True: cand_node = -1 cand_dist = float('inf') for i in xrange(1, N + 1): if not seen[i] and dist[i] < cand_dist: cand_dist = dist[i] cand_node = i if cand_node < 0: break seen[cand_node] = True for nei, d in graph[cand_node]: dist[nei] = min(dist[nei], dist[cand_node] + d) ans = max(dist.values()) return ans if ans < float('inf') else -1 |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |