class Solution {
public int[] sumOfDistancesInTree(int N, int[][] edges) {
final int INF = 0x3f3f3f3f;
int [][]graph=new int[N][N];
for(int i=0;i<N;i++){
Arrays.fill(graph[i],INF);//
}
for(int []edge:edges){
graph[edge[0]][edge[1]] = 1;
graph[edge[1]][edge[0]] = 1;
}
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(i == j) continue;
graph[i][j] = Math.min(graph[i][j],graph[i][k]+graph[k][j]);
}
}
}
int []res=new int[N];
for(int i=0;i<N;i++){
res[i]=0;
for(int j=0;j<N;j++){
if(i==j)continue;
res[i]+=graph[i][j];
}
}
return res;
}
}
每日算法:弗洛伊德算法
最新推荐文章于 2024-10-24 16:59:13 发布