dfs深度优先搜索
来源:互联网 发布:linux自动挂载 编辑:程序博客网 时间:2024/05/01 19:06
#include <stdio.h>#include <string.h>int G[10][5];int book[10][10];int sum =0;void dfs(int x,int y,int step);int main(){<span style="white-space:pre"></span>memset(G,0,sizeof(G));<span style="white-space:pre"></span>G[2][1] = 1;<span style="white-space:pre"></span>G[3][0] = 1;<span style="white-space:pre"></span>G[5][0] = 1;<span style="white-space:pre"></span>G[6][1] = 1;<span style="white-space:pre"></span>G[4][2] = 1;<span style="white-space:pre"></span>G[2][3] = 1;<span style="white-space:pre"></span>G[6][3] = 1;<span style="white-space:pre"></span>G[3][4] = 1;<span style="white-space:pre"></span>G[5][4] = 1;<span style="white-space:pre"></span>book[0][0]=1;<span style="white-space:pre"></span>dfs(0,0,0);<span style="white-space:pre"></span>printf("%d",sum);<span style="white-space:pre"></span>getchar();<span style="white-space:pre"></span><span style="white-space:pre"></span><span style="white-space:pre"></span>return 0;}void dfs(int x,int y,int step){<span style="white-space:pre"></span>int next[2][2]={1,0,0,1};<span style="white-space:pre"></span>int tx,ty,k;<span style="white-space:pre"></span>if(x == 1 && y==2)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>sum++;<span style="white-space:pre"></span>return;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>for(k = 0; k<2;k++)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>tx = x + next[k][0];<span style="white-space:pre"></span>ty = y + next[k][1];<span style="white-space:pre"></span>if(tx < 0 || tx > 8||ty<0||ty > 4)<span style="white-space:pre"></span>continue;<span style="white-space:pre"></span>if(G[tx][ty]==0 && book[tx][ty] ==0)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>book[tx][ty] = 1;<span style="white-space:pre"></span>dfs(tx,ty,step+1);<span style="white-space:pre"></span>book[tx][ty]=0;<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>}<span style="white-space:pre"></span>return;}
book[tx][ty]=1代表走过.若下一步不能走了那么返回上一个的dfs函数处,使上一个book[tx][ty]=0; 尝试向下走。
book[tx][ty] 无非就是一个标识,代表tx,ty能不能走,k代表的方向,0为右,1为下。
具体算法是:判断右方是否能走,能走则往右走,不能走则判断下是否能走,下也不能走则返回上一个步骤,上一个步骤判断下是否能走,不能走再返回上上一个.直到返回第一步,判断是否 能下走,不能,最后return退出dfs();如果找到目标,那么返回上一步,向下走,同样的。。
详细可以参考 啊哈算法P81
0 0
- 深度优先搜索 DFS
- 深度优先搜索 DFS
- DFS 深度优先搜索
- DFS 深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- DFS深度优先搜索
- 深度优先搜索(DFS)
- dfs深度优先搜索
- dfs 深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- DFS深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- 深度优先搜索(DFS)
- 深度优先搜索--DFS
- getline( cin,s,'\n' )不能读取最后一条输入的问题
- Fragment生命周期
- ecshop验证码不显示
- Struts2 笔记3
- CF 二分
- dfs深度优先搜索
- STM32f103 看门狗使用
- 利用select函数实现非阻塞式的socket accept
- C++实验3—定期存款利息计算器
- 链式栈
- JAVA+Selenium环境配置进行web页功能自动化的测试
- 关于mysql事件处理的方法
- JAVA中HashMap如何删除元素
- 产品经理从娃娃抓起