1
+ // from source node to destination node atleat k distance should be there;
2
+ #include < iostream>
3
+ #include < vector>
4
+ using namespace std ;
5
+ typedef pair<int , int >edge;
6
+ class Graph {
7
+ int V;
8
+ vector<edge>* adj;
9
+ bool helper (int u, int k, vector<bool >& path) {
10
+ if (k <= 0 ) return true ;
11
+ for (auto [v, w] : adj[u]) {
12
+ if (path[v]) continue ; // if current node exits in path i.e hence cycle; so ignore this path;
13
+ if (w >= k) return true ; // if curr edge weight is more than k hence it itself make path more than k hence return true;
14
+ path[v] = true ; // take this node in path
15
+ if (helper (v, k - w, path)) return true ; // remove w from requrired k;
16
+ path[v] = false ; // if including this node not found path hence make it false and try next node;
17
+ }
18
+ // if any of the adjacent node of u did not find path >= k hence return false;
19
+ return false ;
20
+ }
21
+ public:
22
+
23
+ Graph (int v) {
24
+ V = v;
25
+ adj = new vector<edge>[V];
26
+ }
27
+ void addEdge (int u, int v, int w) {
28
+ adj[u].push_back ({ v,w });
29
+ adj[v].push_back ({ u,w });
30
+ }
31
+ bool pathMoreThanK (int u, int k) {
32
+ vector<bool > path (V, false );
33
+ path[u] = 1 ;
34
+ return helper (u, k, path);
35
+ }
36
+ };
37
+ int main () {
38
+ // create the graph given in above figure
39
+ int V = 9 ;
40
+ Graph g (V);
41
+
42
+ // making above shown graph
43
+ g.addEdge (0 , 1 , 4 );
44
+ g.addEdge (0 , 7 , 8 );
45
+ g.addEdge (1 , 2 , 8 );
46
+ g.addEdge (1 , 7 , 11 );
47
+ g.addEdge (2 , 3 , 7 );
48
+ g.addEdge (2 , 8 , 2 );
49
+ g.addEdge (2 , 5 , 4 );
50
+ g.addEdge (3 , 4 , 9 );
51
+ g.addEdge (3 , 5 , 14 );
52
+ g.addEdge (4 , 5 , 10 );
53
+ g.addEdge (5 , 6 , 2 );
54
+ g.addEdge (6 , 7 , 1 );
55
+ g.addEdge (6 , 8 , 6 );
56
+ g.addEdge (7 , 8 , 7 );
57
+
58
+ int src = 0 ;
59
+ int k = 62 ;
60
+ cout << (g.pathMoreThanK (src, k) ? " Yes\n " : " No\n " );
61
+
62
+ k = 60 ;
63
+ cout << (g.pathMoreThanK (src, k) ? " Yes\n " : " No\n " );
64
+ return 0 ;
65
+ }
66
+ // https://leetcode.com/playground/LbdfKDz5
0 commit comments