# http://acm.nyist.net/JudgeOnline/problem.php?pid=58

bfs搜索水题进行时~~~~

#include<iostream>
#include<string.h>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
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 dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct point
{
int x;
int y;
int step;
}po;
bool visit[10][10];
int sx,sy,ex,ey;
int step;
int bfs(int x,int y)
{
memset(visit,false,sizeof(visit));
queue<point>q;
po.x=x;po.y=y;po.step=0;
q.push(po);
visit[x][y]=true;
while(!q.empty())
{
po=q.front();
q.pop();
x=po.x;y=po.y;step=po.step;
if(x==ex&&y==ey) return step;
for(int i=0;i<4;++i)
{
int x1=x+dx[i];
int y1=y+dy[i];
if(!map[x1][y1]&&!visit[x1][y1]&&x1>=0&&x1<=8&&y1>=0&&y1<=8)
{ po.x=x1;po.y=y1;po.step=step+1;q.push(po);
visit[x1][y1]=true;
}
}
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>sx>>sy>>ex>>ey;
cout<<bfs(sx,sy)<<endl;
}return 0;
}

dfs

#include<iostream>
#include<string.h>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
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 dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct point
{
int x;
int y;
int step;
}po;
int sx,sy,ex,ey;
int step,minstep;
void dfs(int x,int y)
{
if(x==ex&&y==ey) {minstep=min(step,minstep);return;}//结束条件
for(int i=0;i<4;++i)
{
int x1=dx[i]+x;
int y1=dy[i]+y;
if(x1>=0&&x1<=8&&y1>=0&&y1<=8&&!map[x1][y1])
{
step++;
map[x1][y1]=1;
dfs(x1,y1);
map[x1][y1]=0;//回溯。。。。
step--;
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{    step=0;
minstep=0xffffff;
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
map[sx][sy]=1;
dfs(sx,sy);
map[sx][sy]=0;
printf("%d\n",minstep);
}return 0;
}

10-25 379

11-08 462

03-02 517

10-22 344

08-23 1684

07-18 107

03-30 435

11-03 602

03-29 405