//
// main.cpp
// DFS in Graph
//
// Created by Himanshu on 27/08/21.
//
#include <iostream>
#include <vector>
using namespace std;
//n = number of nodes in graph
void DFS (int x, int n, vector<int> graph[], int vis[]) {
vis[x] = 1;
cout<<x<<" ";
for (int i=0; i<graph[x].size(); i++) {
int j = graph[x][i];
if (vis[j] == 0) {
DFS(j, n, graph, vis);
}
}
}
int main() {
int s = 1, n = 6;
vector<int> graph[n+1];
int vis[n+1];
graph[1].push_back(2);
graph[2].push_back(1);
graph[2].push_back(4);
graph[3].push_back(5);
graph[4].push_back(2);
graph[4].push_back(5);
graph[4].push_back(6);
graph[5].push_back(3);
graph[5].push_back(4);
graph[6].push_back(4);
for (int i=1; i<=n; i++) {
vis[i] = 0;
}
cout<<"Graph:"<<endl;
for (int i=1; i<=n; i++) {
cout<<i<<": ";
for (int j=0; j<graph[i].size(); j++) {
cout<<graph[i][j]<<" ";
}
cout<<endl;
}
cout<<endl<<"DFS:"<<endl;
DFS(s, n, graph, vis);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBERlMgaW4gR3JhcGgKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjcvMDgvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDx2ZWN0b3I+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgovL24gPSBudW1iZXIgb2Ygbm9kZXMgaW4gZ3JhcGgKdm9pZCBERlMgKGludCB4LCBpbnQgbiwgdmVjdG9yPGludD4gZ3JhcGhbXSwgaW50IHZpc1tdKSB7CiAgICB2aXNbeF0gPSAxOwogICAgY291dDw8eDw8IiAiOwogICAgZm9yIChpbnQgaT0wOyBpPGdyYXBoW3hdLnNpemUoKTsgaSsrKSB7CiAgICAgICAgaW50IGogPSBncmFwaFt4XVtpXTsKICAgICAgICBpZiAodmlzW2pdID09IDApIHsKICAgICAgICAgICAgREZTKGosIG4sIGdyYXBoLCB2aXMpOwogICAgICAgIH0KICAgIH0Kf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