介绍
以广度为准,先访问从岔道能直接到达的所有结点,然后再按这些结点被访问顺序访问它们能直接到达的结点,直至全部遍历完。
求矩阵中元素上下左右均为1所组成的块的数目
#include <iostream>
#include <queue>
using namespace std;
const int maxn=100;
int x,y;
int str[maxn][maxn];//矩阵
bool enter[maxn][maxn]={false};//是否已入队
struct node{//结点位置int x;int y;
}nodes;
//两个数组分别表示上下左右移动
int str1[]={0,0,-1,1};
int str2[]={1,-1,0,0};
//判断是否需要访问
bool judge(int a,int b){if(a<0||a>x||b<0||b>y)//越界return false;if(enter[a][b]==true||str[a][b]==0)//已被入过队或访问值不为1,return false;return true;
}
void BFS(int x,int y){queue<node> q;nodes.x=x;nodes.y=y;q.push(nodes);enter[x][y]=true;while(!q.empty()){nodes=q.front();q.pop();for(int i=0;i<4;i++){//看其上下左右是否满足条件int newX=nodes.x+str1[i];int newY=nodes.y+str2[i];if(judge(newX,newY)){nodes.x=newX;nodes.y=newY;q.push(nodes);//满足就入队enter[newX][newY]=true;//表示已入队}}}
}
int main(){int count=0;cin>>x>>y;for(int i=0;i<x;i++)for(int j=0;j<y;j++)cin>>str[i][j];for(int i=0;i<x;i++)for(int j=0;j<y;j++){if(enter[i][j]==false&&str[i][j]==1){count++;BFS(i,j);}}cout<<count<<endl;return 0;
}
走迷宫:’ * ‘表示墙,’ . '表示平地,只能上下左右移动,求由起点出发到达终点的最少步数。
#include <iostream>
#include <queue>
using namespace std;
const int maxn=100;
int x,y,count=0;
char str[maxn][maxn];
struct node{int x;int y;int step;//记录每个位置下的步数
}b,e;
node nodes;//临时结点
bool enter[maxn][maxn]={false};
int str1[]={0,0,-1,1};
int str2[]={1,-1,0,0};
bool judge(int a,int b){//判断是否为有效位置if(a<0||a>=x||b<0||b>=y) return false;if(enter[a][b]==true)//已入过return false;if(str[a][b]=='*')//墙return false;return true;
}
int BFS(){queue<node> q;q.push(b);while(!q.empty()){node top=q.front();q.pop();if(top.x==e.x&&top.y==e.y)return top.step;//到达终点返回步数for(int i=0;i<4;i++){int newX=top.x+str1[i];int newY=top.y+str2[i];if(judge(newX,newY)){//判断新元素是否为有效位置nodes.x=newX;nodes.y=newY;nodes.step=top.step+1;//找到一个步数++q.push(nodes);enter[newX][newY]=true;}}}return -1;
}
int main(){cin>>x>>y;//对输入的处理for(int i=0;i<x;i++){getchar();//去掉每行中的换行符for(int j=0;j<y;j++){str[i][j]=getchar();}str[i][y+1]='\0';//手动添加结束符}cin>>b.x>>b.y>>e.x>>e.y;b.step=0;cout<<BFS()<<endl;return 0;
}