数据结构与算法9: 图的广度优先搜索
图的广度优先搜索是指每次都访问完一个节点的全部未被访问过的相邻节点,再去访问其中一个相邻节点的全部相邻的未访问节点。广度优先搜索是一个不断扩大范围的过程。广搜可以使用队列实现。
使用邻接表表示图。C++。
#include <iostream>
#include <queue>
#define MAX 100
using namespace std;
typedef struct ptr
{
int pos;
struct ptr* next;
} ptr;
struct node
{
char data;
int visited;
ptr* p;
};
int n;
void createGraph(struct node g[])
{
int i, j, eNum, pos;
ptr* p1;
ptr* p2;
printf("How many nodes:");
scanf("%d", &n);
for (i = 0; i < n; ++i)
{
printf("%dth node:", i);
getchar();
scanf("%c", &g[i].data);
g[i].visited = 0;
g[i].p = NULL;
printf(" How many edges:");
scanf("%d", &eNum);
for (j = 0; j < eNum; ++j)
{
printf("%dth edge:", j);
scanf("%d", &pos);
p2 = (ptr*)malloc(sizeof(ptr));
p2->pos = pos;
p2->next = NULL;
if (g[i].p != NULL)
{
p1->next = p2;
p1 = p2;
}
else
{
g[i].p = p2;
p1 = p2;
}
}
}
}
void bfs(struct node g[], int pos)
{
queue<int> q;
ptr* p;
q.push(pos);
while (!q.empty())
{
g[q.front()].visited = 1;
printf("%d ", g[q.front()]);
p = g[q.front()].p;
while (p)
{
if (g[p->pos].visited == 0)
q.push(p->pos);
p = p->next;
}
q.pop();
}
}
int main()
{
struct node g[MAX];
createGraph(g);
bfs(g, 0);
return 0;
}