这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
2 3 1 5 7 3 1 6 7
12 11
最近好久没做搜索的题了,感觉手都有点生了,拿这个题练练手,水题一个,直接用dfs就可以直接水过,也可以用bfs做,对bfs还是很熟练啊,这道题思路还是很清晰的,走过就标记,但是开始那个计数的没控制好,导致一直没结果,还有就是dfs用递归写,一定要控制好递归的结束情况,不然到时候都不知道错在哪,还是要温故而知新啊,对以前学过的东西还是要经常复习一下;
下面是水过的代码;
#include <cstdio>
#include <cstring>
#define min(x,y) x>y?y:x //这种写法是参考别人的
using namespace std;
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int map[9][9]={
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
int c,d,m;
void dfs(int a,int b,int ans)
{
int x,y;
if(a==c&&b==d)
{
m=min(m,ans);
return ; //返回,递归结束,返回上一层;
}
map[a][b]=1;//标记走过的路径
for(int i=0;i<4;i++)
{
x=a+dir[i][0];
y=b+dir[i][1];
if(map[x][y]==0)//对路径进行判断
{
dfs(x,y,ans+1);//再次搜索
map[x][y]=0;
}
}
}
int main()
{
int n,a,b;
scanf("%d",&n);
while(n--)
{
m=9999;//这里用一个比较大的数和计数的进行比较;
scanf("%d%d%d%d",&a,&b,&c,&d);
dfs(a,b,0);
map[a][b]=0;
printf("%d\n",m);
}
return 0;
}nyist oj 58 最少步数(dfs搜索),布布扣,bubuko.com
原文:http://blog.csdn.net/whjkm/article/details/38356119