您的位置:首页 > 其它

nyoj 58 最小步数(bfs)

2015-10-23 10:30 344 查看
初入手搜索,慢慢来,学算法不能着急

本题从某一点开始广搜.就是把上下左右可能的点都遍历,看看有没有合适的点,如果有,就放入队列,然后4个方向判断完成后,再从队首取出一个元素,接着进行,注意:当队列为空时,说明搜索结束仍然没有找到目标点。 这里的广搜和树的层序遍历极为相似,大家可以先看下树的层序建立,层序遍历,思路一致。

# include<cstdio>
# include<cstdlib>
# include<string.h>
# include<algorithm>
# include<iostream>
# 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 vis[9][9];
int fx[4][2]={0,1,0,-1,1,0,-1,0};
struct node{
int x,y,temp;
};
int bfs(int a,int b,int c,int d){
if(a==c && b==d) return 0;
struct node start={a,b,0};
struct node next;
queue<struct node> q;
q.push(start);
while(!q.empty()){
start=q.front();
q.pop();
for(int i=0;i<4;i++){
next.x=start.x+fx[i][0];
next.y=start.y+fx[i][1];
next.temp=start.temp+1;
if(next.x>=0 && next.x<9 && next.y>=0 && next.y<9 && map[next.x][next.y]==0 && vis[next.x][next.y]==0){
vis[next.x][next.y]=1;
if(next.x==c && next.y==d) return next.temp;
else {
q.push(next);
}

}
}

}

}

int main(void){

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: