套用模板,进行广搜。
#include#include #include #include using namespace std;#define INFINITY 0#define MAX_VERTEX_NUM 6001 //顶点最多个数#define LENGTH 20 //顶点字符长度//*********************************邻接表***********************************begintypedef char VertexType[LENGTH];typedef struct ArcNode{ int adjvex; struct ArcNode* nextarc; int weight;}ArcNode;typedef struct VNode{ VertexType data; ArcNode *firstarc;}VNode, AdjList[MAX_VERTEX_NUM];typedef struct{ AdjList vertices; int vexnum; int arcnum;}ALGraph;int Judge(char *s1,char *s2){ int n1=strlen(s1); int n2=strlen(s2); if(n1!=n2) return 0; int count=0; for(int i=0;i >g.vertices[i].data){ g.vertices[i].firstarc = NULL; i++; } g.vexnum=i; ArcNode *p, *q; ArcNode *pTmp; g.arcnum=0; for (int i = 0; i < g.vexnum; i++){ for(int j = i+1;j < g.vexnum;j++){ if(Judge(g.vertices[i].data,g.vertices[j].data)){ g.arcnum++; int x = i; int y = j; p = new ArcNode; q = new ArcNode; p->adjvex = y; p->nextarc = NULL; p->weight = 1; q->adjvex = x; q->nextarc = NULL; q->weight = 1; if (NULL == g.vertices[x].firstarc) g.vertices[x].firstarc = p; else{ for (pTmp = g.vertices[x].firstarc; NULL != pTmp->nextarc; pTmp = pTmp->nextarc); pTmp->nextarc = p; } if (NULL == g.vertices[y].firstarc) g.vertices[y].firstarc = q; else{ for (pTmp = g.vertices[y].firstarc; NULL != pTmp->nextarc; pTmp = pTmp->nextarc); pTmp->nextarc = q; } } } }}//v的第一个邻接点int FirstAdjVex(const ALGraph &g, int v){ if ( NULL != g.vertices[v].firstarc) return g.vertices[v].firstarc->adjvex; return -1;}//v相对于w的下一个邻接点int NextAdjVex(const ALGraph &g, int v, int w){ ArcNode *p; for (p = g.vertices[v].firstarc; NULL != p; p = p->nextarc) if (p->adjvex == w && p->nextarc != NULL) return p->nextarc->adjvex; return -1;}//*********************************邻接表***********************************endbool visit[MAX_VERTEX_NUM];//广度优先遍历int pre[MAX_VERTEX_NUM];void BFSTraverse(ALGraph &g, char vName1[LENGTH],char vName2[LENGTH]){ memset(pre,-1,sizeof(pre)); int pos = LocateVex(g, vName1); for (int v = 0; v < g.vexnum; v++) visit[v] = false; queue q; if (!visit[pos]){ pre[pos]=-1;//cout< <<'\t';//访问 visit[pos] = true; } q.push(pos); int v,w; while (!q.empty()){ v = q.front(); q.pop(); for (w = FirstAdjVex(g, v); w >= 0; w = NextAdjVex(g, v, w)){ if (!visit[w]){ //cout< <<'\t';//访问 pre[w]=v; visit[w] = true; if(strcmp(g.vertices[w].data,vName2)==0) break; q.push(w); } } if(strcmp(g.vertices[w].data,vName2)==0) break; } //cout<