-
Notifications
You must be signed in to change notification settings - Fork 0
/
Check_for_path_more_than_K_length_from_source.cpp
91 lines (73 loc) · 1.99 KB
/
Check_for_path_more_than_K_length_from_source.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> iPair;
class Graph
{
int V;
list<pair<int, int>> *graph;
public:
Graph(int V)
{
this->V = V;
graph = new list<iPair>[V];
}
void addEdge(int u, int v, int w)
{
graph[u].push_back(make_pair(v, w));
graph[v].push_back(make_pair(u, w));
}
bool findPath(int source, int k, vector<bool> &visited)
{
visited[source] = true;
if (k == 0)
return true;
for (auto i : graph[source])
{
int u = i.first;
int weight = i.second;
// if the current node is already visited, then there is loop in this path. So continue to next path.
if(visited[u])
continue;
// current weight is itself greater than K-value then this path is the answer.
if (weight >= k)
return true;
// if we haven't got our answer, we will make dfs-call but the current K-value
// will be k - (sum of path till now) which is (k - weight)
if (findPath(u, k - weight, visited))
return true;
}
// Backtracking:
visited[source] = false;
return false;
}
bool pathMoreThanK(int source, int k)
{
vector<bool> visited(V, false);
return findPath(source, k, visited);
}
};
int main()
{
int V = 9;
Graph g(V);
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
int source = 0;
int k = 62;
g.pathMoreThanK(source, k) ? cout << "Yes\n" : cout << "No\n";
k = 60;
g.pathMoreThanK(source, k) ? cout << "Yes\n" : cout << "No\n";
return 0;
}