ronith
10/23/2018 - 3:14 AM

If there is a path of more than k length from a source

//https://www.geeksforgeeks.org/find-if-there-is-a-path-of-more-than-k-length-from-a-source/
#include <bits/stdc++.h>
using namespace std;

class graph {
    int v;
    list < pair<int,int> > *adj;
public:
    graph (int v) {
        this->v= v;
        adj= new list < pair<int,int> > [v];
    }
    void addEdge (int u, int w, int x) {
        adj[u].push_back(make_pair(w,x));
        adj[w].push_back(make_pair(u,x));
    }
    bool dfs (int ,bool [], int );
};

bool graph::dfs (int s, bool visited[], int k) {
    if (k<=0)
        return 1;

    visited[s]= 1;
    list < pair<int,int> >::iterator i;
    for (i= adj[s].begin(); i!= adj[s].end(); ++i) {
        int w= (*i).first;
        int x= (*i).second;
        if (visited[w])
            continue;
        if (x>=k)
            return 1;
        if (!visited[w] && dfs(w, visited, k-x))
            return 1;
    }
    visited[s]= 0;
    return 0;

}

int main() {
    graph g(9);
    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);


    bool visited[9]= {0};
    if (g.dfs(0,visited, 62))
        cout<< "Possible!";
    else
        cout<< "Not Possible!";
}