首页 > 其他 > 详细

用queue函数写广搜

时间:2017-04-29 19:41:19      阅读:370      评论:0      收藏:0      [点我收藏+]

以走迷宫需要的最少步数的代码为例

#include<stdio.h>
#include<string.h>
#include<queue>

using namespace std;

struct Note{
int x,y,s;
};
int a[51][51],book[51][51];

void bfs(Note h, Note t)
{
int Next[4][2] = {0};
int i,tx,ty;
Note head,tail;
queue<Note> q;
q.push(h);
book[h.x][h.y] = 1;
while(!q.empty()){
head = q.front();
q.pop();
for(i = 0; i < 4; i++){
tx = head.x + Next[i][0];
ty = head.y + Next[i][1];
if(tx < 0 || tx >= t.x || ty < 0 || ty >= t.y)
continue;
if(a[tx][ty] == 0 && book[tx][ty] == 0){
tail.x = tx;
tail.y = ty;
q.push(tail);
book[tx][ty] = book[head.x][head.y] + 1;
}
if(tx == t.x && ty == t.y)
return ;
}
}
}

int main()
{
Note head,tail;
int i,j,n,m;
while(scanf("%d%d",&n,&m) != EOF){
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
scanf("%d",&a[i][j]);
memset(book,0,sizeof(book));
scanf("%d%d%d%d",&head.x,&head.y,&tail.x,&tail.y);
head.s = 0;
bfs(head,tail);
printf("%d\n",book[tail.x][tail.y]);
}
return 0;
}

用queue函数写广搜

原文:http://www.cnblogs.com/didideblog/p/6785818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!