#include<iostream>
#include<stdio.h>
#include<queue>
#define MAX 5
#define INF 100;
using namespace std;
typedef struct {
int data;
}vertex;
typedef struct{
int edge[MAX][MAX];
vertex v[MAX];
int n,e;
}MGraph; //邻接矩阵存储
typedef struct node{
int adjvex;
struct node * next;
}ANode; //边节点
typedef struct{
int data;
ANode * firstarc;
}VNode;
typedef VNode Adjlist[MAX];
typedef struct{
Adjlist adjlist;
int n,e;
}ALGraph; // 邻接表存储
void MatToList(MGraph g,ALGraph * & G){
int i,j;
ANode * p;
G=new ALGraph;
for(i=0;i<g.n;i++){
G->adjlist[i].firstarc=NULL;
}
for(i=0;i<g.n;i++){
for(j=g.n-1;j>=0;j--){
if(g.edge[i][j]!=0){
p=new ANode;
p->adjvex=j;
p->next=G->adjlist[i].firstarc; //使用头插法插入,保证与与原顺序一致
G->adjlist[i].firstarc=p;
}
}
}
G->n=g.n;
G->e=g.e;
}
int visited[MAX]={0};
void dfs(ALGraph * G,int vertex){ //深度优先遍历
ANode * p;
visited[vertex]=1;
p=G->adjlist[vertex].firstarc;
cout<<vertex<<" ";
while(p!=NULL){
if(visited[p->adjvex]==0){
dfs(G,p->adjvex); //深度优先
}
p=p->next; //查找邻接点
}
}
void bfs(ALGraph * G,int v){ //广度优先遍历
queue<int> q; //队列
int w,i;
ANode * p;
int visited[MAX];
for(i=0;i<G->n;i++){
visited[i]=0;
}
visited[v]=1;
cout<<v<<" ";
q.push(v); //将初始节点入队
while(!q.empty()){
w=q.front();
p=G->adjlist[w].firstarc;
q.pop();
while(p!=NULL){
if(visited[p->adjvex]==0){
q.push(p->adjvex);
cout<<p->adjvex<<" ";
visited[p->adjvex]=1;
}
p=p->next;
}
}
}
int visit[MAX];
void ExitPath(ALGraph * G,int u,int v,bool & has){ //判断顶点u和顶点v之间是否存在路径
int w;
ANode * p;
visit[u]=1;
if(u==v){
has=true;
return ;
}
p=G->adjlist[u].firstarc;
while(p!=NULL){
w=p->adjvex;
if(visit[w]==0){
ExitPath(G,w,v,has);
}
p=p->next;
}
}
int visit2[MAX];
void findPath(ALGraph * G,int u,int v,int path[],int d){ //输出从u到v的所有简单路径
int w,i;
ANode * p;
visit2[u]=1;
d++; //初始值为-1
path[d]=u;
if(u==v&&d>=1){ //若要输出长度为n的路径,使d==n即可
for(i=0;i<=d;i++){
if(i==0)
cout<<path[i];
else
cout<<"-->"<<path[i];
}
cout<<endl;
}
p=G->adjlist[u].firstarc;
while(p!=NULL){
w=p->adjvex;
if(visit2[w]==0)
findPath(G,w,v,path,d);
p=p->next;
}
visit2[u]=0; //恢复环境
}
int main(){
int i,j,k=0;
MGraph g;
ALGraph * G;
g.n=MAX;
g.e=MAX;
for(i=0;i<MAX;i++){
g.v[i].data=i;
}
for(i=0;i<MAX;i++){
for(j=0;j<MAX;j++){
g.edge[i][j]=0; //初始化邻接矩阵
}
}
cout<<"input i-->j : "<<endl; //输入边对应的顶点
while(k<MAX){
cin>>i>>j;
g.edge[i][j]=1;
k++;
}
cout<<"built map is : "<<endl; //输出邻接矩阵
for(i=0;i<MAX;i++){
for(j=0;j<MAX;j++)
cout<<g.edge[i][j]<<" ";
cout<<endl;
}
MatToList(g,G); //将邻接矩阵转换为邻接表
cout<<"dfs road is : "<<endl;
dfs(G,0);
cout<<endl;
cout<<"bfs road is : "<<endl;
bfs(G,0);
cout<<endl;
bool has=false;
cout<<"input i-->j to judge whether they has road ?"<<endl;
cin>>i>>j;
ExitPath(G,i,j,has);
int path[MAX],d=-1;
if(has){
cout<<"has road : "<<endl;
findPath(G,i,j,path,d);
}
else{
cout<<"don't has road ."<<endl;
}
cout<<endl;
for(i=0;i<MAX;i++)
cout<<visit2[i]; //visit2数组已经全部被还原为0
return 0;
}
/*
test data:
0 1
0 3
3 2
1 2
2 4
*/