示例程序
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <queue> using namespace std; struct node { int data; struct node * next; }; //定义全局变量 int m, k, t, visit[1010]; struct node * head[1010], * p; //每一个节点都对应自己的一个头结点 void BFS(int x) { int y; struct node * p, * q; for(int i = 0; i < k; i++) //同一个结点的同层邻接点,节点编号小的优先遍历 { for(p = head[i]->next; p != NULL; p = p->next) //冒泡排序,把编号小的节点优先遍历 { for(q = p->next; q != NULL; q = q->next) { int temp = p->data; p->data = q->data; q->data = temp; } } } queue<int>Q; //STL,调用队列 Q.push(x); visit[x] = 1; //访问遍历完成,就把访问标志遍历赋值为1 while(!Q.empty()) { cout << (y = Q.front()) << " "; //输出队头数据,并且队头出列 Q.pop(); for(p = head[y]->next; p != NULL; p = p->next) //根据顶点索引,遍历此时顶点中的所有节点 { if(visit[p->data] == 0) //未遍历访问的赋值,入列 { visit[p->data] = 1; Q.push(p->data); } } } } int main() { int n; cin >> n; while(n--) { memset(visit, 0, sizeof(visit)); //初始化访问标志数组 cin >> m >> k >> t; for(int i = 0; i < k; i++) //初始化每个顶点的队头 { head[i] = (struct node *)malloc(sizeof(struct node)); head[i]->next = NULL; } for(int i = 0; i < k; i++) { int u, v; cin >> u >> v; p = (struct node *)malloc(sizeof(struct node)); //类似于逆序建立链表,根据顶点索引,把与之相关联的节点存入到链表中 p->data = u; p->next = head[v]->next; head[v]->next = p; p = (struct node *)malloc(sizeof(struct node)); //同上 p->data = v; p->next = head[u]->next; head[u]->next = p; } BFS(t); cout << endl; } return 0; }
