8000 add c++ solution (Dijkstra's algorithm) in algorithms/cpp/networkDela… · royeLin/leetcode_cpp@85be23e · GitHub
[go: up one dir, main page]

Skip to content

Commit 85be23e

Browse files
committed
add c++ solution (Dijkstra's algorithm) in algorithms/cpp/networkDelayTime/networkDelayTime.cpp
1 parent eab6201 commit 85be23e

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Source : https://leetcode.com/problems/network-delay-time/
2+
// Author : Sunny Lin
3+
// Date : 2023-06-07
4+
5+
/**********************************************************************************
6+
*
7+
Utilize Dijkstra's algorithm
8+
*/
9+
10+
#include <stdio.h>
11+
#include <stdlib.h>
12+
13+
#include <iostream>
14+
#include <vector>
15+
#include <algorithm>
16+
#include <queue>
17+
#include <limits>
18+
using namespace std;
19+
20+
#define INF numeric_limits<int>::max()
21+
22+
struct cmp
23+
{
24+
bool operator()(pair<int, int>a, pair<int, int>b){
25+
return a.second > b.second;
26+
}
27+
};
28+
29+
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
30+
31+
vector<vector<pair<int, int>>> adjlist(n);
32+
for(auto & time: times){
33+
adjlist[time[0] - 1].push_back({time[1] - 1, time[2]});
34+
}
35+
36+
vector<int> _distance(n, INF);
37+
_distance[k - 1] = 0;
38+
39+
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp>q;
40+
q.push({k - 1, 0});
41+
42+
while (!q.empty())
43+
{
44+
int current_vertex = q.top().first;
45+
q.pop();
46+
for(auto& adj_neighbor: adjlist[current_vertex]){
47+
int neighboring_vertex = adj_neighbor.first;
48+
int weight = adj_neighbor.second;
49+
if(_distance[neighboring_vertex] > ( _distance[current_vertex] + weight)){
50+
_distance[neighboring_vertex] = _distance[current_vertex] + weight;
51+
q.push({neighboring_vertex, _distance[neighboring_vertex]});
52+
}
53+
}
54+
}
55+
int min_time = *max_element(_distance.begin(), _distance.end());
56+
if(min_time == INF) return -1;
57+
return min_time;
58+
}
59+

0 commit comments

Comments
 (0)
0