先簡單回顧一下,今天預計分析的題目:
題目敘述
測資的 Input/Output
首先利用 Floyd-Warshall 計算任兩城市間的最短路徑長。此處建立 distance
陣列用以紀錄 DP 狀態
# Initialize
distance = [ [ float('inf') ] * n for i in range(n) ]
for i in range(n): distance[i][i] = 0
for i in edges:
distance[i[0]][i[1]] = i[2]
distance[i[1]][i[0]] = i[2]
distance
# Floyd-Warshall
for i in range(n):
for j in range(n):
for k in range(n):
distance[j][k] = min(distance[j][i] + distance[i][k], distance[j][k])
# Count Neighbor
countNeighbor = [len(list(filter(lambda x: x <= distanceThreshold, distance[i]))) - 1 for i in range(n)]
return min(range(n), key=lambda x: (countNeighbor[x], -x))
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# Initialize
distance = [ [ float('inf') ] * n for i in range(n) ]
for i in range(n): distance[i][i] = 0
for i in edges:
distance[i[0]][i[1]] = i[2]
distance[i[1]][i[0]] = i[2]
# Floyd-Warshall
for i in range(n):
for j in range(n):
for k in range(n):
distance[j][k] = min(distance[j][i] + distance[i][k], distance[j][k])
# Count Neighbor
countNeighbor = [len(list(filter(lambda x: x <= distanceThreshold, distance[i]))) - 1 for i in range(n)]
return min(range(n), key=lambda x: (countNeighbor[x], -x))