先上个模板
有点类似树的层序遍历,其实层序遍历也可以看作是一种广度优先搜索。
void bfs(int s){
//定义队列q,并将起点s入队
queue<int> q;
q.push(s);
while(!q.empty()){//队列非空时
取队首元素top;//先取出队首元素进行操作
访问队首元素top;
将队首元素出队;
//将top下一层的未入队节点全部入队,并且设置为已经入队
将top的下一层节点中未曾入队的节点全部入队;
}
}
例题1
给出一个m*n的矩阵,矩阵元素为0或1.求1构成的矩阵块
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
#include<iostream>
#include<queue>
using namespace std;
const int maxn=110;
struct node{
int x,y;
}nod;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,-1,1};
//代表四个方向,这题也是个四连通问题
int martix[maxn][maxn];
//martix数组存放矩阵
int n,m;
//矩阵的两维度
bool mp[maxn][maxn];
//标记数组
bool judge(int x,int y){
//越界了返回0
if(x>=n||x<0||y>=m||y<0) return false;
//没有1或者已经访问过了返回0
if(martix[x][y]==0||mp[x][y]==1) return false;
//返回1
return true;
}
void bfs(int x,int y){//广搜
queue<node> q;
nod.x=x;
nod.y=y;//赋值
q.push(nod);//第一个节点入队
mp[x][y]=true;//已访问
while(!q.empty()){
node top=q.front();
//取队首元素
q.pop();
//遍历四个方向
for(int i=0;i<4;i++){
int newx=top.x+dx[i];
int newy=top.y+dy[i];
if(judge(newx,newy)){
//继续搜索,注意这里
//把这里的广度搜索想象成水波纹
//一圈圈地荡漾开
nod.x=newx;
nod.y=newy;//更新坐标
q.push(nod);//压入队中
mp[newx][newy]=true;//已访问
}
}
}
}
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>martix[i][j];
}
}
int ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(martix[i][j]==1&&mp[i][j]==false){
ans++;
bfs(i,j);
}
}
}
cout<<ans;
return 0;
}
例题2
迷宫问题
给定一个n * m大小的迷宫,其中 * 代表不可通过的墙壁,而 . 代表平地,S代表起点,T代表终点。
注意:只能四方向移动
求最少步数。
输入
5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3
输出
11
注意与例题1的区别,这题求的是最少步数,而bfs是通过层序来遍历的,因此可以从起点开始对层次计数,那么在达到终点T的时候的层数就是步数。
#include<cstdio>
#include<queue>
const int maxn=110;
struct node{
int x,y;
int step;
}S,T,nod;//起点,终点,中间节点
int n,m;
char maze[maxn][maxn];
bool mp[maxn][maxn];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
bool judge(int x,int y){
if(x<0||x>=n||y<0||y>=m) return false;
if(maze[x][y]=='*'||mp[x][y]==1) return false;
return true;
}
int bfs(){
queue<node> q;
q.push(S);
while(!q.empty()){
node top=q.front();
q.pop();
if(top.x==T.x&&top.y==T.y) return top.step;
//达到终点返回步数
for(int i=0;i<4;i++){
int newx=top.x+dx[i];
int newy=top.y+dy[i];
if(judge(newx,newy)){
nod.x=newx;
nod.y=newy;
nod.step=top.step+1;
q.push(nod);
mp[newx][newy]=true;
}
}
}
return -1;
}
int main(){
scanf("%d%d%*c",&n,&m);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%c",&maze[i][j]);
}
scanf("%*c");
}
scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);
S.step=0;
printf("%d",bfs());
return 0;
}