图遍历之广度优先搜索

4. 广度优先搜索(BFS)

算法演示地址为:http://sjjg.js.zwu.edu.cn/SFXX/sf1/gdyxbl.html

伪代码如下:

图遍历之广度优先搜索_第1张图片

c完整代码如下:

/* bfs.c */
#include <stdio.h>
#include "queue.h"

#define N 6

struct adj_matrix {
	int vertex[N];
	int edge[N][N]; 
};

struct adj_matrix matrix = {
	{1, 2, 3, 4, 5, 6},

	{{0, 1, 0, 1, 0, 0},
	 {0, 0, 0, 0, 1, 0},
	 {0, 0, 0, 0, 1, 1},
	 {0, 1, 0, 0, 0, 0},
	 {0, 0, 0, 1, 0, 0},
	 {0, 0, 0, 0, 0, 1}}
};

int visit[N] = {0, 0, 0, 0, 0, 0};

void bfs(struct adj_matrix *G)
{
	int i, j;
	int x;

	for (i = 0; i < N; i++) {
		if (visit[i] != 1) {
			visit[i] = 1;

			printf("%3d", G->vertex[i]);

			enqueue(i);
			while (!queue_empty()) {
				x = dequeue();
				for (j = 0; j < N; j++) {
					if (G->edge[x][j] == 1 && visit[j] != 1) {
						visit[j] = 1;
						printf("%3d", G->vertex[j]);
						enqueue(j);
					}
				}
			}
		}
	}
}

int main(void)
{
	bfs(&matrix);
	printf("\n");

	return 0;
}

其中用到了队列,队列部分代码如下:

/* queue.c */
#include <stdio.h>
#include <limits.h>

#define QUEUE_LENGTH 128

struct queue {
	int head;
	int tail;
	int size;

	int buf[QUEUE_LENGTH];
};

struct queue Q;

int queue_empty(void)
{
	return Q.size == 0; 
}

int queue_full(void)
{
	return Q.size == QUEUE_LENGTH;
}

int dequeue(void)
{
	int x;

	if (queue_empty()) {
		printf("Queue underflow!\n");
		return INT_MIN;
	}

	x = Q.buf[Q.head];
	Q.size--;

	if (Q.head == QUEUE_LENGTH - 1) {
		Q.head = 0;
	} else {
		Q.head++;
	}

	return x;
}

void enqueue(int x)
{
	if (queue_full()) {
		printf("Queue overflow!\n");
		return;
	}

	Q.buf[Q.tail] = x;
	Q.size++;

	if (Q.tail == QUEUE_LENGTH - 1) {
		Q.tail = 0;
	} else {
		Q.tail++;
	}
}
头文件为:

/* queue.h */
#ifndef __QUEUE_H
#define __QUEUE_H

/* Queue API */
void enqueue(int x);
int dequeue(void);
int queue_empty(void);
int queue_full(void);

#endif /* __QUEUE_H */

遍历结果为:  1  2  4  5  3  6

你可能感兴趣的:(图遍历之广度优先搜索)