Description
试基于图的深度优先搜索策略编写程序,判别以邻接表方式存储的有向图中,是否存在由顶点vi到顶点vj的路径(i不等于j)。注意:程序中涉及的图的基本操作必须在此存储结构上实现。
Input
第一行输入有向图的顶点数n和边数m,用空格隔开;第二行输入顶点信息;分m行输入有向图边的信息,例如顶点对1,2表示从顶点1到顶点2的一条弧。最后一行输入待判别的顶点对vi,vj.(0<m,n<100)
Output
若有向图中存在由顶点vi到顶点vj的路径(i不等于j),则输出yes;否则输出no。
Sample input
4 4
1 2 3 4
1 2
1 3
1 4
2 3
Sample output
yes
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode//邻接表结点
{
int v,tag;
struct lnode *next;
}lnode;
typedef struct tnode//表头结点
{
int v,tag;
lnode *head;
}tnode;
typedef struct graph
{
tnode h[20];
int n,m;
}graph;
void DFS(graph g,int vi,int vj,int *t)
{
lnode *p;
if(g.h[vi].head){
p=g.h[vi].head;
while(p){
if(p->tag==0){
p->tag=1;
if(p->v==vj) break;
else{
if(*t==1) break;
else DFS(g,p->v,vj,t);
}
}
else p=p->next;
}
if(p&&p->v==vj) printf("yes"),*t=1;
}
}
int main()
{
graph g;
lnode *p;
int i,a,b,vi,vj,*t;
t=(int*)malloc(sizeof(int));
*t=0;
scanf("%d %d",&g.n,&g.m);
for(i=0;i<g.n;i++){
scanf("%d",&g.h[i].v);
g.h[g.h[i].v].head=NULL;
}
for(i=0;i<g.m;i++){//建立邻接表
scanf("%d %d",&a,&b);
p=(lnode*)malloc(sizeof(lnode));
if(g.h[a].head==NULL){
p->v=b,p->tag=0,p->next=NULL,g.h[a].head=p;
}
else{
p->v=b,p->tag=0,p->next=g.h[a].head->next,g.h[a].head->next=p;
}
}
scanf("%d %d",&vi,&vj);
DFS(g,vi,vj,t);
if(*t!=1) printf("no");
return 0;
}
又是自己瞎编的,编完看了看老师的,觉得老师的简单的多……下次一定先看笔记。