用临接矩阵存储图,输出深度优先遍历的顶点序列:
#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct
{
int n,e;
}Graph;
Graph G;
int Adj[50][50];
int visited[50];
int dfs(Graph G,int v)
{
int w;
visited[v]=1;
printf(“%d”,v);
for(w=1;w<=G.n;w++)
{
if(Adj[v][w]==1&&visited[v]==0)
dfs(G,w);
}
}
int main(int argc, char *argv[])
{
inti,j;
scanf(“%d%d”,&G.n,&G.e);
for(i=1;i<=G.n;i++)
for(j=1;j<=G.n;j++)
{
scanf(“%d”,&Adj[i][j]);
}
for(i=1;i<=G.n;i++)
visited[i]=0;
for(i=1;i<=G.n;i++)
dfs(G,i);
system(“PAUSE”);
returnEXIT_SUCCESS;
}
用邻接表存储图,输出深度优先遍历的顶点序列
#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct ArcNode//表结点的类型定义
{
int adjvex;//该弧所指向的顶点的位置
struct ArcNode *nextarc;//指向下一弧的指针
}ArcNode;
typedef struct
{
ArcNode *firstarc;//指向第一条依附该顶点的弧的指针
}AdjList[50]; //头结点
typedef struct
{
int vexnum,arcnum,weight;
AdjList vertices;
}Graph; //图的存储结构定义
Graph g;
int n,e;
int visited[50];
int dfs(Graph g,int v)
{
int w;
ArcNode*p;
visited[v]=1;
printf(“%d”,v);
for(p=g.vertices[v].firstarc;p;p=p->nextarc)
if(w=p->adjvex&&visited[w]==0)dfs(g,w);
}
int dfstraves(Graph g)
{
int v;
memset(visited,0,sizeof(visited));
for(v=0;v<n;++v)
if(visited[v]==0) dfs(g,v);
}
int create(Graph g)
{
inti,j;
ArcNode*p;
for(i=0;i<n;i++)
{
g.vertices[i].firstarc=NULL;
}
for(i=0;i<e;i++)
{
scanf(“%d%d%d”,&g.vexnum,&g.arcnum,&g.weight);
p=g.vertices[g.vexnum].firstarc;
while(p!=NULL) p=p->nextarc;
p=(ArcNode *)malloc(sizeof(ArcNode));//p 原来指向NULL现在要方一些数据,必须有空间
p->adjvex=g.arcnum;
p->nextarc=NULL;
}
}
int main(int argc, char *argv[])
{
scanf(“%d%d”,&n,&e);
create(g);
dfstraves(g);
system(“PAUSE”);
returnEXIT_SUCCESS;
}