8000 add c++ solution (Bellman-Ford algorithm) in algorithms/cpp/networkDe… · royeLin/leetcode_cpp@21d11df · GitHub
[go: up one dir, main page]

Skip to content

Commit 21d11df

Browse files
committed
add c++ solution (Bellman-Ford algorithm) in algorithms/cpp/networkDelayTime/networkDelayTime2.cpp
1 parent 85be23e commit 21d11df

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Source : https://leetcode.com/problems/network-delay-time/
2+
// Author : Sunny Lin
3+
// Date : 2023-06-07
4+
5+
/**********************************************************************************
6+
*
7+
Utilize Bellman-Ford 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+
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
23+
24+
vector<int> _distance(n, INF);
25+
_distance[k - 1] = 0;
26+
27+
for(int i{}; i < n-1; i++){
28+
for(auto & source_target_time :times){
29+
int source = source_target_time[0];
30+
int target = source_target_time[1];
31+
int weight = source_target_time[2];
32+
if(_distance[source - 1] != INF and _distance[target -1] > _distance[source -1] + weight){
33+
_distance[target - 1] = _distance[source -1] + weight;
34+
}
35+
}
36+
}
37+
38+
int min_time = *max_element(_distance.begin(), _distance.end());
39+
if(min_time == INF) return -1;
40+
return min_time;
41+
}
42+

0 commit comments

Comments
 (0)
0