-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs using adjacency matrix.cpp
More file actions
94 lines (87 loc) · 2.31 KB
/
bfs using adjacency matrix.cpp
File metadata and controls
94 lines (87 loc) · 2.31 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<bits/stdc++.h>
using namespace std;
bool visited[8];
void initialize()
{
for(int i=0 ; i<8 ; i++)
visited[i]=false;
}
void printAdj_Mat(int adj[][8])
{
for(int i=0 ; i<8 ; i++)
{
for(int j=0 ; j<8 ; j++)
cout<<adj[i][j]<<' ';
cout<<endl;
}
}
void bfs(int adj[][8],int s)
{
initialize();
queue<int> q;
q.push(s);
visited[s]=true;
while(!q.empty())
{
int temp=q.front();
q.pop();
for(int i=0 ; i<8 ; i++)
{
if(adj[temp][i]==1)
{
if(!visited[i])
{
q.push(i);
cout<<i<<' ';
visited[i]=true;
}
}
}
}
}
int main()
{
cout<<" GRAPH";
cout<<"\n 0";
cout<<"\n / | \\";
cout<<"\n / | \\";
cout<<"\n / | \\";
cout<<"\n / | \\";
cout<<"\n 1 2 3";
cout<<"\n / \\ / \\ /";
cout<<"\n / \\ / \\/";
cout<<"\n 4 5 6 7";
int adj_undir[8][8]={
0,1,1,1,0,0,0,0,
1,0,0,0,1,1,0,0,
1,0,0,0,0,0,1,1,
1,0,0,0,0,0,0,1,
0,1,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,
0,0,1,1,0,0,0,0
};
int adj_dir[8][8]={
0,1,1,1,0,0,0,0,
0,0,0,0,1,1,0,0,
0,0,0,0,0,0,1,1,
0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0
};
int s;
cout<<"\n\nEnter source node : ";
cin>>s;
if(s>7)
{
cout<<"Invalid source node !";
return 0;
}
cout<<"\nUndirected Graph"<<endl;
cout<<"Traversal order : ";bfs(adj_undir,s);
cout<<"\n\nDirected Graph(top to bottom)"<<endl;
cout<<"Traversal order : ";bfs(adj_dir,s);
return 0;
}