forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
47 lines (43 loc) · 1.19 KB
/
Solution.cpp
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
37
38
39
40
41
42
43
44
45
46
47
class Graph {
public:
Graph(int n, vector<vector<int>>& edges) {
this->n = n;
g = vector<vector<int>>(n, vector<int>(n, inf));
for (auto& e : edges) {
int f = e[0], t = e[1], c = e[2];
g[f][t] = c;
}
}
void addEdge(vector<int> edge) {
int f = edge[0], t = edge[1], c = edge[2];
g[f][t] = c;
}
int shortestPath(int node1, int node2) {
vector<bool> vis(n);
vector<int> dist(n, inf);
dist[node1] = 0;
for (int i = 0; i < n; ++i) {
int t = -1;
for (int j = 0; j < n; ++j) {
if (!vis[j] && (t == -1 || dist[t] > dist[j])) {
t = j;
}
}
vis[t] = true;
for (int j = 0; j < n; ++j) {
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
return dist[node2] >= inf ? -1 : dist[node2];
}
private:
vector<vector<int>> g;
int n;
const int inf = 1 << 29;
};
/**
* Your Graph object will be instantiated and called as such:
* Graph* obj = new Graph(n, edges);
* obj->addEdge(edge);
* int param_2 = obj->shortestPath(node1,node2);
*/