題目
思路:
- 要找的點是可到達的點的距離在 threshold 裡的那些點,所以要找的是最短距離,因為只要最短距離可以在 threshold 內,那它就是可到達的點
- 用 Floyd-Warshall’s algorithm 找到所有點之間的最小距離
k是i到j之間的任意點。比較i->j經過所有k的距離,最小的即為i->j的最短距離。- Question:
if the path isi -> 2 -> 1 -> jand the iteration considerk == 1first. But thedist[i][1]not yet populated and still have value offloat('inf'). It will have the actual value untilk == 2.- Answer from ChatGPT:
- You’ve identified a key aspect of the Floyd-Warshall algorithm’s iterative process. The algorithm relies on the gradual building of shortest paths through each possible intermediate vertex, and the order of considering vertices (the k values) doesn’t prevent it from eventually finding the shortest paths.
- In your example, even if k == 1 is considered first and the direct path i -> 1 or 1 -> j isn’t the shortest, the algorithm might not immediately find the shortest path i -> 2 -> 1 -> j. However, when k == 2 is later considered, the algorithm will then take into account paths through 2, updating the shortest path calculations accordingly.
- The crux of the Floyd-Warshall algorithm is that by the time all vertices have been iteratively considered as potential intermediate steps, it will have computed the shortest paths between all pairs of vertices, considering all possible intermediate vertices and paths.
- Answer from ChatGPT:
- 比較每個點在 threshold 內可達的點的個數,找出最小的&有最大 number 的點
1 | def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: |
- 要注意一下
dist[i][j] = dist[j][i] = w蠻容易漏掉中間那個dist[j][i]