Untitled
unknown
plain_text
3 years ago
2.4 kB
5
Indexable
// BFS DFS ::
#include <bits/stdc++.h>
using namespace std;
class Edge{
public:
int src;
int dest;
};
class Graph
{
public:
vector<vector<int>> adjList;
Graph(vector<Edge> &edges, int v)
{
adjList.resize(v);
for(auto &edge: edges)
{
adjList[edge.src].push_back(edge.dest);
adjList[edge.dest].push_back(edge.src);
}
}
};
void recursiveBFS(Graph &graph, queue<int> &q, vector<bool> &discovered)
{
if(q.empty())
{
return;
}
int v = q.front();
q.pop();
cout<<v<<" ";
for(int u: graph.adjList[v])
{
if(!discovered[u])
{
discovered[u] = true;
q.push(u);
}
}
recursiveBFS(graph, q, discovered);
}
void DFS(Graph &graph, int v, vector<bool> &discovered)
{
discovered[v] = true;
cout<<v<<" ";
for(int u: graph.adjList[v])
{
if(!discovered[u])
{
DFS(graph, u, discovered);
}
}
}
int main()
{
vector<Edge> edge;
int v,e;
int source;
int destination;
cout<<"Enter the number of vertices and edges in graph : ";
while(true)
{
if(cin>>v>>e)
{
break;
}
cin.clear();
cin.ignore(1000, '\n');
cout<<"Enter again!"<<endl;
}
cout<<"Enter the source and destination of the edges : "<<endl;
for(int i=0 ; i<e ; i++)
{
if(cin>>source>>destination && source<v+1 && destination<v+1)
{
// if(source<v && destination<v)
// {
edge.push_back({source,destination});
// break;
}
else{
cin.clear();
cin.ignore(1000, '\n');
cout<<"This vertex not present !";
i--;
}
// }
}
Graph graph(edge,v+1);
vector<bool> discovered1(v+1,false);
vector<bool> discovered2(v+1,false);
queue<int> q;
int stratnode;
cout<<"Enter the starting node : ";
cin>>stratnode;
q.push(stratnode);
discovered1[stratnode] = true;
cout<<"BFS : "<<endl;
recursiveBFS(graph,q,discovered1);
cout<<endl;
cout<<"DFS : "<<endl;
if(discovered2[stratnode] == false){
DFS(graph, stratnode, discovered2);}
}Editor is loading...