forked from spandey1296/Learn-Share-Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS_Adjacency.cpp
104 lines (103 loc) ยท 1.62 KB
/
BFS_Adjacency.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
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
95
96
97
98
99
100
101
102
103
104
#include <bits/stdc++.h>
#include <iostream>
#define MAX 30
class Queue
{
int arr[MAX];
int front;
int rear;
public:
Queue()
{
front = -1;
rear = -1;
}
void enQueue(int item)
{
rear++;
arr[rear] = item;
}
void deQueue()
{
front++;
// return arr[front];
}
int peak()
{
return arr[front+1];
}
int isFull()
{
if (rear == MAX - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (front == rear)
return 1;
else
return 0;
}
void display()
{
for (int i = rear; i >= front + 1; i--)
{
cout << arr[i] << " ";
}
cout << endl;
}
};
using namespace std;
const int v = 6;
int unvisitedNeighbor(int index,int graph[v][v],int visited[]){
for(int i=0; i<v; i++){
if(graph[index][i] == 1 && (visited[i] == 0)){
return i;
}
}
return -1;
}
void bfs(int graph[v][v], int a)
{
int visited[v];
for (int i = 0; i < v; i++)
visited[i] = 0;
Queue q;
q.enQueue(a);
visited[a] = 1;
int vis;
while (!q.isEmpty())
{
vis = q.peak();
cout << vis << " ";
q.deQueue();
int neighbor_Vertex;
while ((neighbor_Vertex = unvisitedNeighbor(vis,graph,visited)) != -1)
{
//Mark neighbors as visited
visited[neighbor_Vertex] = 1;
q.enQueue(neighbor_Vertex);
}
}
}
int main()
{
ifstream infile;
infile.open("bfs_adj_matrix.txt", ios::in);
int graph[v][v];
for (int i = 0; i < v; i++)
for (int j = 0; j < v; j++)
infile >> graph[i][j];
bfs(graph, 0);
return 0;
}
/**
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 1 1
0 1 1 1 0 1
0 0 0 1 1 0
**/