您的位置:首页 > 其它

DFS && BFS 最少步数(nyoj 58)

2016-07-29 16:30 417 查看
最少步数


最少步数

时间限制:3000 ms  |  内存限制:65535 KB
难度:4

描述

这有一个迷宫,有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)。)

输入第一行输入一个整数n(0<n<=100),表示有n组测试数据;

随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7


样例输出
12
11


DFS:

<span style="font-size:18px;">
#include<cstdio>
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 sum;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int x,y;

void dfs(int a,int b,int count){
if (a==x&&b==y){
if (count<sum)
sum=count;

}
else{
for (int i=0;i<4;i++){
int xx=a+dx[i];
int yy=b+dy[i];
if (map[xx][yy]==0&&count+1<sum){
map[xx][yy]=1;
dfs(xx,yy,count+1);
map[xx][yy]=0;
}
}

}

}

int main(){
int n;
int a,b;
scanf ("%d",&n);
while (n--){
scanf ("%d %d %d %d",&a,&b,&x,&y);
int count=0;
map[a][b]=1;
sum=10000;
dfs(a,b,count);
map[a][b]=0;
printf ("%d\n",sum);
}
return 0;

}        </span>


BFS:

<span style="font-size:18px;">#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
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,
};

struct node{
int x,y,step;
}s,end,now;
int vis[9][9];
int n,a,b,c,d;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};

int bfs(){
s.x = a;s.y=b;s.step=0;
vis[a][b]=true;
queue<node>q;
q.push(s);
while (!q.empty()){
now = q.front();
q.pop();
if (now.x==c && now.y==d){
return now.step;
}
for (int i=0;i<4;i++){
end.x=dx[i]+now.x;
end.y=dy[i]+now.y;
end.step=now.step;
if (map[end.x][end.y]==0&&!vis[end.x][end.y]){//少写!vis[][],超内存
end.step++;
vis[end.x][end.y]=true;
q.push(end);
}
}
}

}
int main(){

scanf ("%d",&n);
while (n--){
scanf ("%d %d %d %d",&a,&b,&c,&d);
memset(vis,false,sizeof(vis));
int ans=bfs();
printf ("%d\n",ans);
}
return 0;

} </span>
区别:BFS搜索到的就是最优解,DFS需要判断更新出最优解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: