2020-01-30 22:22:58
Problem Description :
Problem Solving :
Solution a: floyd
The subject is a look floyd most suitable solution, because it is required a multi-source shortest, floyd algorithm is the most appropriate, time complexity is O (n ^ 3).
int inf = (int)1e9; public int findTheCity(int n, int[][] edges, int distanceThreshold) { int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) Arrays.fill(dp[i], inf); for (int i = 0; i < n; i++) { dp[i][i] = 0; } for (int[] edge : edges) { int u = edge[0]; int v = edge[1]; int d = edge[2]; dp[u][v] = d; dp[v][u] = d; } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j] > dp[i][k] + dp[k][j]) { dp[i][j] = dp[i][k] + dp[k][j]; } } } } List<int[]> note = new ArrayList<>(); for (int i = 0; i < n; i++) { int cnt = 0; for (int j = 0; j < n; j++) { if (dp[i][j] <= distanceThreshold) cnt += 1; } note.add(new int[]{i, cnt}); } Collections.sort(note, new Comparator<int[]>(){ public int compare(int[] o1, int[] o2) { return o1[1] == o2[1] ? o2[0] - o1[0] : o1[1] - o2[1]; } }); return note.get(0)[0]; }