-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
161 lines (151 loc) · 3.1 KB
/
BFS.cpp
File metadata and controls
161 lines (151 loc) · 3.1 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#include<iostream>
#include<queue>
#include<cmath>
#include<ctime>
using namespace std;
int n;
int matrix[1001][1001];
bool visited[1001];
int flag = 0;
void Standard()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
matrix[j][i] = matrix[i][j];
}
}
}
void Input()
{
cout << "\nEnter number vertex of graph: ";
cin >> n;
int flag;
cout << "\nMenu: \n\t1.Manual Input \n\t2.Automatic Random\n===================================";
do {
cout << "\nChoose your input method: ";
cin >> flag;
} while (flag < 1 || flag > 2);
if (flag == 1)
{
cout << "\n\t===== Manual Input =====";
for (int i = 0; i < n; i++)
{
cout << "\nVertex " << i + 1 << ":\n";
for (int j = 0; j <= i; j++)
{
if (i == j)
matrix[i][j] = 0;
else
{
do {
cout << "\tv" << j + 1 << ": ";
cin >> matrix[i][j];
} while (matrix[i][j] < 0 || matrix[i][j] > 1);
}
}
}
Standard();
}
else if (flag == 2)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == j)
matrix[i][j] = 0;
else
matrix[i][j] = rand() % 2 - 0;
}
}
Standard();
}
}
int GetEdges()
{
int k = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
k = k + matrix[i][j];
}
return k;
}
void Output()
{
cout << endl;
cout << " _";
for (int i = 0; i < n - 1; i++)
{
cout << " ";
}
cout << " _";
cout << endl;
for (int i = 0; i < n - 1; i++)
{
cout << " | ";
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << "|";
if (i == (n / 2) - 1)
{
cout << " = G(" << n << ";" << GetEdges() << ")";
}
cout << endl;
}
cout << " |_ ";
for (int i = 0; i < n; i++)
{
cout << matrix[n - 1][i];
if (i == n - 1)
cout << " _|";
else cout << " ";
}
}
void BFS(int u)
{
cout << "BFS(" << u << "): ";
queue<int> Q;
Q.push(u);
visited[u] = true;
flag++;
while (!Q.empty())
{
int v = Q.front();
cout << v << " ";
Q.pop();
for (int t = 1; t <= n; t++)
{
if (visited[t] == false && matrix[v][t] == 1)
{
Q.push(t);
visited[t] = true;
flag++;
break;
}
}
}
}
void Report()
{
if (flag == n)
cout << "\n\tThe Graph: Connected!";
else cout << "\n\tThe Graph: NOT Connected!";
}
int main()
{
int s;
Input();
Output();
cout << "\n\nSelect starting vertex: ";
cin >> s;
BFS(s);
Report();
cout << endl;
system("pause");
return 0;
}