Network Delay Time

There are N network nodes, labelled 1 to N.

Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, vis the target node, and w is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.

Note:

  1. N will be in the range [1, 100].
  2. K will be in the range [1, N].
  3. The length of times will be in the range [1, 6000].

  1. All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.

给定一个有向图,权值是时间,问从给定节点走遍其他所有节点花费的时间

使用Dijkstra算法,找到给定点到其他所有节点的时间代价,最长的就是答案。注意在存储有向图时,需要注意,可能会给同一条边多次赋值,需要存储最小的。

Dijkstra简介:每一次找到没有走到的最近的节点,并使用这一节点更新到其他没有走到的节点的距离

class Solution {
    public int networkDelayTime(int[][] times, int N, int K) {
        int[][] distance = new int[N + 1][N + 1];
        for(int[] it : distance)
        	Arrays.fill(it, 99999999);
        for(int[] it : times){
        	int i = it[0], j = it[1];
        	int temp = Math.min(distance[i][j], it[2]);
        	distance[i][j] = temp;
        }
        for(int i = 1; i < N + 1; i++)
        	distance[i][i] = 0;
        boolean[] visited = new boolean[N + 1];
        for(int ct = 0; ct < N; ct++){
        	int min = -1;
        	for(int i = 1; i < N + 1; i++){
        		if(visited[i])
        			continue;
        		if(min == -1 || distance[K][i] < distance[K][min])
        			min = i;
        	}
        	if(distance[K][min] == 99999999)
        		break;
        	visited[min] = true;
    		for(int i = 1; i < N + 1; i++){
    			if(!visited[i] && distance[K][min] + distance[min][i] < distance[K][i]){
    				distance[K][i] = distance[K][min] + distance[min][i];
    			}
    		}
        }
        int ans = 0;
        distance[K][0] = 0;
        for(int it : distance[K]){
        	ans = Math.max(ans, it);
        	//System.out.print(it + " ");
        }
        return ans == 99999999 ? -1 : ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值