/* breadth-first traversal by using a queue
* @method: use queue
* Graph is stored in an adjacency matrix
*/
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
int queue[MAX];
int front=-1; //队头元素前一个位置
int rear=-1; //队尾元素
void enqueue(int k)
{
if(rear < MAX-1)
{
queue[++rear] = k;
}
else
{
printf("queue overflow\n");
exit(-1);
}
}
int dequeue(void)
{
if(front == rear)
{
printf("queue underflow\n");
exit(0);
}
return queue[++front];
}
/* breadth-first-traverse
* @method: 先访问与node相邻的所有节点,并一次入对。再取队中元素做相同操作
*/
void bfs(int x, int visited[], int adj[][MAX], int n)
{
int i, count;
int node;
node = x;
visited[node] = 1;
printf("visit node %d\n", node);
count = 1;
while(count < n)
{
for(i=0; i<n; i++)
{
if(adj[node][i] == 1 && visited[i] == 0)
{
visited[i] = 1;
printf("visit node %d\n", i);
count++;
enqueue(i);
}
}
node = dequeue();
}
}
main(void)
{
int adj[MAX][MAX] = {{0, 1, 1, 0, 0},
{1, 0, 0, 1, 0},
{1, 0, 0, 0, 1},
{0, 1, 0, 0, 0},
{0, 0, 1, 0, 0}
};
int n = 5;
char start_node;
int visited[MAX];
memset(visited, 0, MAX*sizeof(int));
//printf("Enter number of nodes in graph: " );
//scanf("%d", &n);
//buildGraph(adj, n);
printf("breadth-first traverse, enter the starting node: ");
while((start_node = getchar()) != EOF)
{
getchar();
memset(visited, 0, MAX*sizeof(int));
printf("recursive: \n");
front = -1;//remember to reset queue
rear = -1;
bfs((int)atoi(&start_node), visited, adj, n);
}
}
图广度优先遍历(队列实现)
原文作者:数据结构之图
原文地址: https://blog.csdn.net/yangjin_unique/article/details/7839223
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/yangjin_unique/article/details/7839223
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。