因为图的广度优先遍历方式是从图的某个顶点开始,由近至远层层拓展的方式遍历图结点的过程,因此图的广度优先遍历的最后一个结点一定是距离该顶点最远的一个结点。
#define MaxSize 10
//邻接表定义
typedef struct ArcNode{
struct ArcNode* nextArc;
int arcNum;
}ArcNode;
typedef struct{
ArcNode* fristArc;
char data;
}VNode;
typedef struct{
VNode adjList[MaxSize];
int n;
int e;
}AGraph;
void initAGraph(AGraph* &G){
G->e = 5;
G->n = 6;
cout<<"data:"<<endl;
for (int i = 0; i < G->n; i++) {
cin>>G->adjList[i].data;
G->adjList[i].fristArc = NULL;
}
cout<<"vi,vj"<<endl;
for (int j = 0; j < G->e; j++) {
int vi,vj;
cin>>vi>>vj;
ArcNode* node = new ArcNode();
node->arcNum = vj;
node->nextArc = G->adjList[vi].fristArc;
G->adjList[vi].fristArc = node;
}
}
void ArcVisit(VNode node){
cout<<"current: "<<node.data<<endl;
}
int visit[MaxSize];
int BFS(AGraph* G,int v){
//recursion terminator
if (G == NULL) {
return -1;
}
int queue[MaxSize];
int front = 0;
int rear = 0;
int num = v;
//root gets into queue;
rear = (rear + 1)%MaxSize;
queue[rear] = num;
ArcVisit(G->adjList[num]);
visit[num] = 1;
ArcNode* node;
//process logic
while(front != rear) {
front = (front + 1)%MaxSize;
num = queue[front];
node = G->adjList[num].fristArc;
while (node) {
if (visit[node->arcNum] == 0) {
ArcVisit(G->adjList[node->arcNum]);
visit[node->arcNum] = 1;
rear = (rear+1)%MaxSize;
queue[rear] = node->arcNum;
}
node = node->nextArc;
}
}
return num;
}
int main(int argc, const char * argv[]) {
AGraph* G = new AGraph();
initAGraph(G);
cout<<"Last:"<< BFS(G, 0)<<endl;
return 0;
}