广度优先遍历最主要的是 利用队列的数据结构。
#include <stdio.h>
#include <stdlib.h>
#define VertexNum 9
struct BFS_Node
{
int v;
struct BFS_Node *next;
};
typedef struct BFS_Node *Graph;
struct BFS_Node BFS_Head[VertexNum];
int g_bfs_visited[VertexNum];
int g_queue[VertexNum];
int front = -1;
int rear = -1;
void bfs_create_graph(int v1, int v2)
{
Graph pointer;
Graph New = (Graph)malloc(sizeof(struct BFS_Node));
if (New != NULL)
{
New->v = v2; /*临近节点*/
New->next = NULL;
pointer = &(BFS_Head[v1]);
while(pointer->next !=NULL)
pointer = pointer->next;
pointer->next = New;
}
}
void bfs_print_graph(struct BFS_Node *BFS_Head)
{
Graph pointer;
pointer = BFS_Head->next;
while (pointer!=NULL)
{
printf("[%d]", pointer->v);
pointer = pointer->next;
}
printf("\n");
}
int dequeue()
{
if (front == rear)/*empty*/
return -1;
else
{
front++;
return g_queue[front];
}
}
int enqueue(int v)
{
if (rear >= VertexNum+1)/*Full*/
return -1;
else
{
rear++;/*队列尾端指针后移*/
g_queue[rear] = v;
return 1;
}
}
void BFS(int v)
{
Graph pointer;
g_bfs_visited[v] = 1; /*已经查找过了*/
enqueue(v);
printf("[%d]==>", v);
while (front != rear)
{
v = dequeue();
pointer = BFS_Head[v].next;
while(pointer != NULL)
{
if (g_bfs_visited[pointer->v] == 0)
{
enqueue(pointer->v);
g_bfs_visited[pointer->v] = 1;
printf("[%d]==>", pointer->v);
}
pointer = pointer->next;
}
}
}
int main(int argc, char **argv)
{
int i = 0;
int BFS_Node[20][2] = {
{1,2}, {2,1}, {1,3}, {3,1},
{2,4}, {4,2}, {2,5}, {5,2},
{3,6}, {6,3}, {3,7}, {7,3},
{4,8}, {8,4}, {5,8}, {8,5},
{6,8}, {8,6}, {7,8}, {8,7}
};
for (i = 0; i < VertexNum; i++)
{
BFS_Head[i].v = i;
BFS_Head[i].next = NULL;
g_bfs_visited[i] = 0;
}
for(i = 0; i < 20; i++)
{
bfs_create_graph(BFS_Node[i][0], BFS_Node[i][1]);
}
printf("++ Graph ++\n");
for (i = 0; i< VertexNum; i++)
{
printf("Ver[%d] : ", i);
bfs_print_graph(&BFS_Head[i]);
}
printf("Bradth-First-Search : \n");
printf("[Begin]==>");
BFS(1);
printf("[End]");
return 0;
}