【问题描述】假设图G采用邻接矩阵存储,设计算法判断u到v之间是否存在路径。
【输入形式】输入表示图的二维数组 u 和 v 的值
【输出形式】输出判断结果,有路径输出1,没有路径输出0
【样例输入】
0 1 1
1 0 1
1 1 0
0 2
【样例输出】
1
【样例说明】
【评分标准】
#include <iostream>
using namespace std;
int visited[100];
struct queue
{
int no;//顶点编号
int parent;//前一个顶点的编号
};
template <typename T>
struct arcnode//边结点类型
{
int adjvex;//该边的终点编号
arcnode*nextarc;// 指向下一条边的指针
T weight;//该边的权值
};
template <typename T>
struct vnode//表头结点类型
{
char data[100];//顶点信息
arcnode<T>*firstarc;//指向第一条边的结点
};
template <typename T>
struct algraph//图的邻接表
{
vnode<T> adjlist[100];//邻接表数组
int n,e;//顶点和边
};
template <typename T>
class graphclass
{
algraph<T>* G;
public:
graphclass();
~graphclass();
bool HasPath(int u,int v);
void creategraph(T a[][3],int n,int e);
private:
void destroygraph();
void HasPath1(int u,int v,bool &has);
};
template <typename T>
graphclass<T>::graphclass()
{
G=NULL;
}
template <typename T>
graphclass<T>::~graphclass()
{
if(G!=NULL)
destroygraph();
}
template<typename T>
void graphclass<T>::creategraph(T a[][3],int n,int e)
{
int i,j;
arcnode<T>*p;
G=new algraph<T>();
G->n=n;G->e=e;
for(i=0;i<G->n;i++)
for(j=G->n-1;j>=0;j--)
if(a[i][j]!=0&&a[i][j]!=10000)
{
p=new arcnode<T>();
p->adjvex=j;p->weight=a[i][j];
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
}
template <typename T>
void graphclass<T>::destroygraph()
{
int i;
arcnode<T>*pre,*p;
for(i=0;i<G->n;i++)
{
pre=G->adjlist[i].firstarc;
if(pre!=NULL)
{
p=pre->nextarc;
while(p!=NULL)
{
delete pre;
pre=p;
p=p->nextarc;
}
delete pre;
}
}
delete G;
}
template<typename T>
bool graphclass<T>::HasPath(int u,int v)
{
int i;
bool has=false;
for(i=0;i<G->n;i++)
visited[i]=0;
HasPath1(u,v,has);
return has;
}
template<typename T>
void graphclass<T>::HasPath1(int u,int v,bool &has)
{
arcnode<T>*p;int w;
visited[u]=1;
p=G->adjlist[u].firstarc;
while(p!=NULL)
{
w=p->adjvex;
if(w==v)
{
has=true;
return;
}
if(visited[w]==0) HasPath1(w,v,has);
p=p->nextarc;
}
}
int main()
{int a[3][3],k=0;
graphclass<int> m;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
cin>>a[i][j];
if(a[i][j]==1) k++;
}
m.creategraph(a,3,k);
int u,v;
cin>>u>>v;
if(m.HasPath(u,v)) cout<<"1";
else cout<<"0";
return 0;
}