Basic dfs code in C++
///La ilaha illellahu muhammadur rasulullah
///******Bismillahir-Rahmanir-Rahim******///
///Abul Hasnat Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#include<bits/stdc++.h>
using namespace std;
vector <int> vec[1000];
bool visited[1000];
void dfs(int source)
{
visited[source] = 1;
for (int i = 0; i < vec[source].size(); i++)
{
int next = vec[source][i];
if (visited[next] == 0)
dfs(next);
}
}
int main()
{
int nodes, edges;
cin >> nodes >> edges;
for (int i = 0; i < edges; i++)
{
int u, v;
cin >> u >> v;
vec[u].push_back(v);
vec[v].push_back(u);
}
dfs(0);
for (int i = 0; i < nodes; i++)
{
if (visited[i] == 1)
{
cout << "Node " << i << " is visited." << endl;
}
else
{
cout << "Node " << i << " is not visited" << endl;
}
}
return 0;
}
No comments