图的深度优先遍历序列
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
图(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; }
相关文章推荐
- 工程实训 银行储蓄系统
- 网站开发基本常识
- 图解https协议
- 浙大 zoj 1654 Place the Robots (二分匹配 + 关于x,y轴的构造边)
- 鼠标滚轮事件----jquery-mousewheel
- ulimit -c unlimited
- Huffman树进行编码和译码
- jsp日期格式化
- Hello world!
- 银行储蓄系统
- 银行储蓄系统
- Linux环境下使用perl编写CGI(httpd)
- 第K回文数
- 2015.07.18[播放音频、视频_1]
- Java Web Service
- 3 分钟的高速体验 Apache Spark SQL
- handsontable-developer guide-cell function
- 检测到在集成的托管管道模式下不适用的ASP.NET设置的解决方法(转)
- android 来电自动接听和自动挂断
- 工程实训-银行储蓄系统