输出无向图的给定起点的先广序列。
输入格式:
输入第一行给出三个正整数,分别表示无向图的节点数N(1<N≤10)、边数M(≤50)和探索起始节点编号S(节点从1到N编号)。
随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号。
输出格式:
输出从S开始的无向图的先广搜索序列,用一个空格隔开,最后也有一个空格;如果为非连通图,再在结尾处另起一行输出一个0,表示此图非连通。
由于广度优先遍历的节点序列是不唯一的,为了使得输出具有唯一的结果,我们约定以表头插入法构造邻接表。
输入样例:
6 8 2
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5
输出样例:
2 3 1 6 4 5
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxVertexNum 1000
int Visited[MaxVertexNum];
int count = 0;
typedef struct ENode* PtrToENode;
struct ENode {
int V1, V2;
};
typedef PtrToENode Edge;
typedef struct AdjVNode* PtrToAdjVNode;
struct AdjVNode {
int AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode {
PtrToAdjVNode FirstEdge;
}AdjList[MaxVertexNum];
typedef struct GNode* PtrToGNode;
struct GNode {
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph CreateGraph(int VertexNum) {
int V;
LGraph Graph;
Graph = (LGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (V = 1; V <= Graph->Nv; V++)
Graph->G[V].FirstEdge = NULL;
return Graph;
}
void InsertEdge(LGraph Graph, Edge E) {
PtrToAdjVNode NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V2;
NewNode->Next = Graph->G[E->V1].FirstEdge;
Graph->G[E->V1].FirstEdge = NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V1;
NewNode->Next = Graph->G[E->V2].FirstEdge;
Graph->G[E->V2].FirstEdge = NewNode;
}
void Visit(int v) {
printf("%d ", v);
count++;
}
void BFS(LGraph Graph, int v) {
if (!Visited[v]) {
PtrToAdjVNode A;
int front = 0, rear = 0;
int Queue[MaxVertexNum];
Visited[v] = 1;
Queue[++rear] = v;
while (front != rear) {
int w;
w = Queue[++front];
Visit(w);
for (A = Graph->G[w].FirstEdge; A; A = A->Next) {
if (!Visited[A->AdjV]) {
Visited[A->AdjV] = 1;
Queue[++rear] = A->AdjV;
}
}
}
}
}
int main() {
LGraph Graph;
Edge E;;
int V, Nv, Ne, i;
scanf("%d%d%d", &Nv, &Ne, &V);
Graph = CreateGraph(Nv);
if (Ne != 0) {
Graph->Ne = Ne;
E = (Edge)malloc(sizeof(struct ENode));
for (i = 1; i <= Graph->Ne; i++) {
scanf("%d%d", &E->V1, &E->V2);
InsertEdge(Graph, E);
}
}
for (i = 1; i <= Graph->Nv; i++)
Visited[i] = 0;
BFS(Graph, V);
if (count < Nv)printf("\n0");
system("pause");
return 0;
}