Floyd算法计算所有点对之间最短路径。注意先遍历k,才能保证计算k之前,k-1的情况都计算完成了。
时间复杂度:O(N^3)
空间复杂度:O(N^2)
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| func findTheCity(n int, edges [][]int, distanceThreshold int) int { d := make([][]int, n)
for i := 0; i < n; i++ { d[i] = make([]int, n) for j := 0; j < n; j++{ if i != j { d[i][j] = math.MaxInt / 2 } } }
for _, edge := range edges { x := edge[0] y := edge[1] z := edge[2]
d[x][y] = z d[y][x] = z }
for k := 0; k < n; k++ { for i := 0; i < n; i++ { for j := 0; j < n; j++ { if k != i && k != j { d[i][j] = min(d[i][j], d[i][k] + d[k][j]) } } } }
minNeighboor := math.MaxInt / 2 ans := 0
for i := 0; i < n; i++ { neighboor := 0 for j := 0; j < n; j++ { if i != j && d[i][j] <= distanceThreshold { neighboor++ } } if neighboor < minNeighboor || (neighboor == minNeighboor && i > ans) { minNeighboor = neighboor ans = i } }
return ans
}
func min(a, b int) int { if (a > b){ return b } return a }
|