您的位置:首页 > 其它

bfs模板

2015-06-05 13:00 211 查看
#include<iostream>
const int INF=1000000;
typedef pair<int,int> P;
char  maze[MAX][MAX];
int N,M;
int sx,xy;
int gx,gy;
int d[MAX][MAX];  //the distance to every point
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int bfs()
{
queue<P> que;
for(int i=0;i<N;++i)
{
for(int j=0;j<M;++j)
{
d[i][j]=INF;  //initialize every point to INF
}
}
que.push(P(sx,sy));
d[sx][sy]=0;
while(que.size())
{
P p=que.front();
que.pop();
if(p.first==gx&p.second==gy)
break;
for(int k=0;k<4;++k)
{
int nx=p.first+dir[k][0];
int ny=p.second+dir[k][1];
if(0<=nx&&nx<N&&0<=ny&&ny<M&&maze[nx][ny]!='#'&&d[nx][ny]==INF)
{
que.push(P(nx,ny));
d[nx][ny]=d[p.first][p.second]+1;
}
}
}
return 0;
}
void solve()
{
int res=bfs();
printf("%d",res);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  模版 算法