dfs深度优先搜索

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值