forked from spandey1296/Learn-Share-Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS_Adjacency.cpp
101 lines (97 loc) ยท 1.54 KB
/
DFS_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
#include <bits/stdc++.h>
#include <iostream>
#include <iostream>
using namespace std;
#define MAX 100
class Stack
{
int arr[MAX];
int top;
public:
Stack()
{
top = -1;
}
bool isFull()
{
if (top == MAX - 1)
return true;
else
return false;
}
bool isEmpty()
{
if (top == -1)
return true;
else
return false;
}
void push(int item)
{
top++;
arr[top] = item;
}
void pop()
{
// int x = arr[top];
top--;
// return x;
}
int peak()
{
return arr[top];
}
};
using namespace std;
const int v = 7;
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;
Stack s;
s.push(a);
visited[a] = 1;
int vis;
while (!s.isEmpty())
{
vis = s.peak();
cout << vis+1 << " ";
s.pop();
int neighbor_Vertex;
while ((neighbor_Vertex = unvisitedNeighbor(vis,graph,visited)) != -1)
{
//Mark neighbors as visited
visited[neighbor_Vertex] = 1;
s.push(neighbor_Vertex);
}
}
}
int main()
{
ifstream infile;
infile.open("dfs_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 1 0 0
1 0 0 1 0 1 0
1 0 0 1 0 0 1
0 1 1 0 1 0 0
1 0 0 1 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
**/