Skip to content

Commit 9c22834

Browse files
committed
GraphBFS
1 parent 9c228ac commit 9c22834

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Algorithm/GraphBFS.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include<iostream>
2+
#include<queue>
3+
using namespace std;
4+
5+
const static int INF = __INT_MAX__;
6+
7+
/*
8+
A B
9+
/ \ /
10+
/ \ /
11+
/ C------D
12+
E /
13+
\ /
14+
\ /
15+
F
16+
*/
17+
18+
int matrix[6][6] = {{INF, INF, 1, INF, 1, INF},
19+
{INF, INF, 1, INF, INF, INF},
20+
{1, 1, INF, 1, INF, INF},
21+
{INF, INF, 1, INF, INF, 1},
22+
{1, INF, INF, INF, INF, 1},
23+
{INF, INF, INF, 1, 1, INF}
24+
};
25+
26+
int visited[6] = {0};
27+
28+
void BFS(queue<char>& s, char ch)
29+
{
30+
if (s.empty())
31+
return;
32+
cout << ch;
33+
for (int i = 0; i < 6; i++)
34+
{
35+
if (matrix[ch - 'A'][i] == 1 && visited[i] == 0)
36+
{
37+
visited[i] = 1;
38+
s.push('A' + i);
39+
}
40+
}
41+
s.pop();
42+
BFS(s, s.front());
43+
}
44+
45+
int main(int argc, char const *argv[])
46+
{
47+
queue<char> s;
48+
char begin = 'A';
49+
cout << "BFS begin from A:\n";
50+
s.push(begin);
51+
visited[0] = 1;
52+
BFS(s, s.front());
53+
cout << endl;
54+
return 0;
55+
}

0 commit comments

Comments
 (0)