深度优先算法(DFS)
2016-05-25 10:08
169 查看
前言:英文缩写为DFS,可笑的是,我最早去HP公司面试做笔试题的时候, 竟然没看出来是什么意思,当然即使知道是这个算法,当时也不太会写。本科都是学过的,就是后来忘记了。
思路说明:理解深度优先算法的关键在于解决“当下该如何做”。至于下一步应该如何做,和当下应该如何做是一样的,对!就是用递归!自己调用自己!
递归函数模型:
4.应用于图的遍历:
这里我们用二位数组储存图,叫做图的邻接矩阵存储法。
运行结果:
Please input n lines and columns and m links to build a matrix!
5 5
Set linked line between nodes!
0 1
Set linked line between nodes!
0 2
Set linked line between nodes!
0 4
Set linked line between nodes!
1 3
Set linked line between nodes!
2 4
[b]0 1 3 2 4
Press any key to continue
思路说明:理解深度优先算法的关键在于解决“当下该如何做”。至于下一步应该如何做,和当下应该如何做是一样的,对!就是用递归!自己调用自己!
递归函数模型:
void dfs(int step) { 判断边界,如果到了边界当然直接返回啦 尝试每一种可能结果for(i=0;i<n;i++) { 处理当前步 继续下一步dfs(step + 1) } 返回 }
4.应用于图的遍历:
这里我们用二位数组储存图,叫做图的邻接矩阵存储法。
#include<stdio.h> int graph[100][100]; int book[100]; int m,n,sum; int que[10000],head,tail; void dfs(int cur) { int i; printf("%d ",cur); sum++; if(sum == n) { return; } for(i=0;i<n;i++) { if(graph[cur][i] == 1 && book[i] == 0) { book[i] = 1; dfs(i); } } return; } int main() { int i,j,m,a,b; printf("Please input n lines and columns and m links to build a matrix!\n"); scanf("%d %d",&n,&m); for(i=0;i<n;i++) for(j=0;j<n;j++) if(i == j) graph[i][j] = 0; else graph[i][j] = 99999999; for(i=0;i<m;i++) { printf("Set linked line between nodes!\n"); scanf("%d %d",&a,&b); graph[a] = graph[b][a] = 1; } book[0] = 1; dfs(0); //bfs(0); return 0; }
运行结果:
Please input n lines and columns and m links to build a matrix!
5 5
Set linked line between nodes!
0 1
Set linked line between nodes!
0 2
Set linked line between nodes!
0 4
Set linked line between nodes!
1 3
Set linked line between nodes!
2 4
[b]0 1 3 2 4
Press any key to continue
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 有关数据库SQL递归查询在不同数据库中的实现方法
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#中的递归APS和CPS模式详解
- C#冒泡法排序算法实例分析
- WinForm实现按名称递归查找控件的方法
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- 使用SqlServer CTE递归查询处理树、图和层次结构
- C#实现的算24点游戏算法实例分析
- C#中的尾递归与Continuation详解
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法