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

#include 

#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;
}

 

你可能感兴趣的:(算法)