首页 > 代码库 > 用queue函数写广搜
用queue函数写广搜
以走迷宫需要的最少步数的代码为例
#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函数写广搜