Graph-BFS-图的广度优先遍历

时间:2022-10-10 06:57:11
#include <iostream>
#include <queue> using namespace std; /*
5 5
1 2
1 3
1 5
2 4
3 5
1 2 3 5 4
--------------------------------
Process exited with return value 0
Press any key to continue . . .
*/ int sum = 1;
int vertx, edge;
int Graph[20][20] = {0}, book[20] = {0}; void BFS()
{
//队列
queue<int> qgraph; //标记第一个元素已经访问,并压入队列中。
book[1] = 1;
qgraph.push(1); //当队列不为空时
while(!qgraph.empty())
{
int x = qgraph.front();
for(int i = 1; i <= vertx; i++)
{
if(Graph[x][i] == 1 && book[i] == 0)
{
sum++;
book[i] = 1;
qgraph.push(i);
}
} cout << qgraph.front() << " ";
qgraph.pop();
} return;
} int main()
{
cin >> vertx >> edge; for(int i = 1; i <= vertx; i++)
{
for(int j = 1; j <= vertx; j++)
{
if(i == j) Graph[i][j] = 0;
Graph[i][j] = 999999;
}
} for(int i = 1; i <= edge; i++)
{
int x, y;
cin >> x >> y;
Graph[x][y] = 1;
Graph[y][x] = 1;
} BFS(); return 0;
}