bfs模板

来源:互联网 发布:手机直播软件排名 编辑:程序博客网 时间:2024/06/11 06:07
#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 pointint 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);}

0 0
原创粉丝点击