Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- #define pb push_back
- class Graph{
- int nodes;
- vector <int> *edges;
- void printAllPath(int src, int dest, bool *visited, int *path, int &pathIdx){
- visited[src] = true;
- path[pathIdx] = src;
- pathIdx++;
- if(src == dest){
- for(int i=0; i<pathIdx; i++){
- cout << path[i] << ' ';
- }
- cout << endl;
- }else{
- for(auto i=edges[src].begin(); i != edges[src].end(); i++){
- if(!visited[*i]){
- printAllPath(*i, dest, visited, path, pathIdx);
- }
- }
- }
- pathIdx--;
- visited[src] = false;
- }
- public:
- Graph(int vertex){
- this->nodes = vertex;
- edges = new vector <int>[vertex + 1];
- }
- void addEdge(int src, int to){
- edges[src].pb(to);
- }
- void printPath(int src, int to){
- int pathIdx = 0;
- bool *visited = new bool[nodes]();
- int *path = new int[nodes]();
- cout << "Path : ";
- printAllPath(src, to, visited, path, pathIdx);
- }
- bool DLS(int src, int dest, int limit){
- if(src == dest){
- return true;
- }
- if(limit <= 0){
- return false;
- }
- for(auto i=edges[src].begin(); i != edges[src].end(); i++){
- if(DLS(*i, dest, limit - 1)){
- return true;
- }
- }
- return false;
- }
- void IDDFS(int src, int dest, int maxDepth){
- for(int i=0; i<=maxDepth; i++){
- if(DLS(src, dest, i)){
- cout << "Node found at level " << i << '!' << endl;
- printPath(src, dest);
- return;
- }
- cout << "No Intended node found from level 0 to level " << i << '!' << endl;
- }
- }
- };
- int main(){
- int edges, from, to, depth;
- cout << "How many edges ? ";
- cin >> edges;
- Graph graph(edges);
- cout << "How many levels are in the tree (root is level zero) ? ";
- cin >> depth;
- cout << "Enter " << edges << " edges (from-to) separated by a space:" << endl;
- while(edges--){
- cin >> from >> to;
- graph.addEdge(from, to);
- }
- cout << "Enter source and destination node: ";
- cin >> from >> to;
- graph.IDDFS(from, to, depth);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement