bfs模板:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
#define N 1000+5
char map[N][N];
bool visit[N][N]; //标记访问
int n, m;
int dx[4]={1, 0, -1, 0};
int dy[4]={0, 1, 0, -1};
struct point //定义结构体
{
int x, y;
int ncount; //记录步数
};
bool check(point a){ //检查是否符合要求
if(a.x>=0&&a.x<n&&a.y>=0&&a.y<m&&!visit[a.x][a.y]) //视具体情况而定
return true;
else
return false;
}
void bfs(point a){
queue<point>q; //定义队列
a.ncount=0; //步数清零
point now, next; //定义两个状态
q.push(a); //将a压入队列
visit[a.x][a.y]=1; //标记已访问
while(!q.empty()){ //判断是否为空队列
now=q.front(); //取出队首元素
if(now==G){ //出现目标状态,此时ncount最小
.......//做出相关处理
return ;
}
for(int i=0; i<4; i++){
next.x=now.x+dx[i];
next.y=now.y+dy[i]; //计算下一个状态
next.ncount=now.ncount+1;
if(check(next)){
q.push(next); //将next压入队列
visit[next.x][next.y]=1;
}
}
q.pop(); //移除队首元素
}
return ;
}
int main(){
...... //相关操作
return 0;
}