#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