-
Notifications
You must be signed in to change notification settings - Fork 1
/
357.cpp
43 lines (37 loc) · 925 Bytes
/
357.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<bits/stdc++.h>
using namespace std;
void addEdge(vector<pair<int,int>> g[],int u,int v,int w=1){
g[u].push_back(make_pair(v,w));
g[v].push_back(make_pair(u,w));
}
void display(vector<pair<int,int>> g[],int V){
for(int i=0;i<V;i++){
for(int j=0;j<g[i].size();j++){
cout<<i<<" to "<<g[i][j].first<<" weight is : "<<g[i][j].second<<"\n";
}
}
}
void dfstraversal(vector<pair<int,int>> g[],int u,vector<bool> &visited){
cout<<u<<" ";
visited[u]=true;
for(int i=0;i<g[u].size();i++){
if(!visited[u]) dfstraversal(g,g[u][i].first,visited);
}
}
void dfs(vector<pair<int,int>> g[],int V){
vector<bool> visited(V,false);
for(int u=0;u<V;u++){
if(!visited[u]) dfstraversal(g,u,visited);
}
}
int main(){
int V=5;
vector<pair<int,int>> g[V];
addEdge(g,1,2,4);
addEdge(g,1,3,5);
addEdge(g,2,4,2);
addEdge(g,0,3);
display(g,V);
dfs(g,V);
return 0;
}