您的位置:首页 > 其它

图的深度优先遍历序列

2015-07-18 10:24 363 查看
Description

图(graph)是数据结构 G=(V,E),其中V是G中结点的有限非空集合,结点的偶对称为边(edge);E是G中边的有限集合。设V={0,1,2,……,n-1},图中的结点又称为顶点(vertex),有向图(directed graph)指图中代表边的偶对是有序的,用(”<”u,v>)代表一条有向边(又称为弧),则u称为该边的始点(尾),v称为边的终点(头)。无向图(undirected graph)指图中代表边的偶对是无序的,在无向图中边(u,v )和(v,u)是同一条边。

输入边构成无向图,求以顶点0为起点的深度优先遍历序列。

Input

第一行为两个整数n、e,表示图顶点数和边数。以下e行每行两个整数,表示一条边的起点、终点,保证不重复、不失败。1≤n≤20,0≤e≤190

Output

前面n行输出无向图的邻接矩阵,最后一行输出以顶点0为起点的深度优先遍历序列,对于任一起点,首先遍历的是终点序号最小的、尚未被访问的一条边。每个序号后输出一个空格。

Sample Input

4 5

0 1

0 3

1 2

1 3

2 3

Sample Output

0 1 0 1

1 0 1 1

0 1 0 1

1 1 1 0

0 1 2 3

#include<cstdio>
#include<iostream>

using namespace std;

int map[21][21];
int used[21];
int n,e;

void dfs(int v,int count)
{
int steak[210],i;
int top=0;
steak[top++]=v;
printf("%d ",v);
used[v]=1;
while(top>0)
{
int x=steak[top-1];
for(i=1;i<n;i++)
{
if(!used[i]&&map[x][i])
{
steak[top++]=i;
printf("%d ",i);
used[i]=1;
count++;
break;
}
}
if(i==n)
top--;
}
if(count<n)
{
for(int i=1;i<n;i++)
if(!used[i])
dfs(i,count);
}
}

int main()
{
// freopen("in.txt","r",stdin);
int x,y;
scanf("%d%d",&n,&e);
for(int i=0;i<e;i++)
{
scanf("%d%d",&x,&y);
map[x][y]=map[y][x]=1;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
printf("%d ",map[i][j]);
printf("\n");
}
dfs(0,0);
printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: