#define MAX_VEX 20
//#define INFINITY 65535
#define INFINITY 0
class Graph
{
public:
Graph();
~Graph(){};
int FirstVex(int i);
int NextVex(int i , int j);
void BFS_Graph(int start,int end);
public:
int vexs[MAX_VEX];
int arcs[MAX_VEX][MAX_VEX];
int vexnum,arcnum;
int pa[MAX_VEX];
};
Graph::Graph()
{
int i ;
int ch1, ch2;
memset(arcs,INFINITY,sizeof(arcs));
memset(pa,0,sizeof(pa));
printf("Enter vexnum arcnum: ");
scanf("%d,%d", &vexnum, &arcnum);
getchar();
printf("Enter %d vexnum.../n", vexnum);
for(i=1; i<=vexnum; i++)
{
printf("vex %d: ", i);
scanf("%d", &vexs[i]);
getchar();
}
printf("Enter %d arcnum.../n", arcnum);
for(i=1; i<=arcnum; i++)
{
printf("arc %d: ", i);
scanf("%d,%d", &ch1, &ch2);
getchar();
arcs[ch1][ch2]=arcs[ch2][ch1]=1;
}
}
int Graph::FirstVex(int sceneid)
{
if ( sceneid > 0 && sceneid <= MAX_VEX)
{
for (int k = 1 ; k<= vexnum ; k++ )
{
if ( arcs[sceneid][k] != INFINITY )
{
return k;
}
}
}
return -1;
}
//return arcs[sceneid][k] != INFINITY ? k : -1;
int Graph::NextVex(int i , int j)
{
int k;
if ( i> 0 && i <= MAX_VEX && j > 0 && j<= MAX_VEX )
{
for (k = j+1 ; k<= vexnum ; k ++ )
{
if ( arcs[i][k] != INFINITY )
{
return k;
}
}
}
return -1;
}
void Graph::BFS_Graph(int start,int end)
{
int visited[MAX_VEX];
int pa[MAX_VEX];
int parent = start;
int k;
int path[MAX_VEX];
int pathlen = 0;
memset(path,0,sizeof(path));
queue<int>q;
memset(visited,0,sizeof(visited));
memset(pa,0,sizeof(pa));
visited[start]= 1;
pa[start] = -1;
q.push(start);
while ( !q.empty())
{
k = q.front();
parent = k ;
q.pop();
for(int j=FirstVex( k); j>=1; j=NextVex( k, j))
if(!visited[j])
{
visited[j]=1;
pa[ vexs[j] ]= parent;
if ( vexs[j] == end)
{
cout<<"找到目标路径"<<endl;
break;
}
q.push( j );
}
}
cout<<"路径如下"<<endl;
parent = end;
while ( parent != -1 )
{
path[pathlen++] =parent;
cout<<parent<<"--";
parent = pa[parent];
}
cout<<endl;
cout<<"path 如下"<<endl;
pathlen = 0 ;
while ( path[pathlen] != 0 )
{
cout<<path[pathlen++]<<"--";
}
}
int _tmain()
{
Graph gGraph;
gGraph.BFS_Graph(3,4);
return 0;
}