数据结构-图的广度优先遍历(BFS)

#include <stdio.h>

#define MAX 6

//使用邻接矩阵 
int matrix[MAX][MAX];  

//图的广度优先遍历 
void BFS(int start) {
	int queue[MAX] = {0};
	int visited[MAX] = {0};  //优先队列 
	int head = 0;
	int tail = 0;
	int i;

	//开始先入队
	queue[tail++] = start;
	visited[start] = 1;

	while (head != tail) {
		int v = queue[head++];
		printf("%d ", v + 1);
		for (i = 0; i < MAX; i++) {
			if (matrix[v][i] == 1) {
				if (visited[i] == 0) {
					queue[tail++] = i;  //入队 
					visited[i] = 1;
				}
			}
		}
	}

}

void inputData() {
	int i, j;
	freopen("data.txt", "r", stdin);
	/*
	0 1 0 0 1 0
	1 0 1 0 1 0
	0 1 0 1 0 0
	0 0 1 0 1 1
	1 1 0 1 0 0
	0 0 0 1 0 0 
	*/
	for (i = 0; i < MAX; i++) {
		for (j = 0; j < MAX; j++) {
			scanf("%d", &matrix[i][j]);
		}
	}
}

int main() {
	
	inputData();
	BFS(1);

	return 0;
}

 

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/ck0816/article/details/60467299
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞