-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0743-network-delay-time.cs
36 lines (31 loc) · 1.15 KB
/
0743-network-delay-time.cs
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
public class Solution {
public int NetworkDelayTime(int[][] times, int n, int k) {
List<(int node, int weight)>[] adjList = new List<(int node, int weight)>[n + 1];
for (var i = 0; i <= n; i++)
{
adjList[i] = new List<(int node, int wht)>();
}
foreach (var time in times)
{
adjList[time[0]].Add((time[1], time[2]));
}
int[] visited = new int[n + 1];
Array.Fill(visited, 0);
PriorityQueue<int, int> queue = new();
queue.Enqueue(k, 0);
int res = 0;
while (queue.TryDequeue(out int node, out int weight))
{
if (visited[node] == 1) continue;
visited[node] = 1;
res = Math.Max(res, weight);
foreach (var adj in adjList[node])
{
var totalWT = weight + adj.weight;
queue.Enqueue(adj.node, totalWT);
}
}
int? visitedCount = visited.Where(e => e == 1)?.Count();
return visitedCount == n ? res : -1;
}
}