题目
寻找有几个块
code
#include<cstdio>
#include <queue>
using namespace std;
const int maxn=100;
struct node{
int x,y;
}Node;
int n,m;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};//记录是否之前入队了
int X[4]={0,0,1,-1};
int Y[4]={0,0,1,-1};
bool judge(int x,int y){//判断坐标是否需要访问
if(x>=n||x<0||y>=m||y<0){
return false;
}
if(matrix[x][y]=0||inq[x][y]==true){
return false;
}
return true;
}
void BFS(int x,int y){
queue<node> Q;
Node.x=x;
Node.y=y;
Q.push(Node);
inq[x][y]=true;//设置为已经入队了
while(!Q.empty()){
node top=Q.front();// 取出队首元素
Q.pop();// 队首元素出队
for(int i=0;i<4;i++){
int newX=top.x+X[i];
int newY=top.y+Y[i];
if(judge(newX, newY)){
Node.x=newX;
Node.y=newY;
Q.push(Node);
inq[newX][newY]=true;
}
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int x=0;x<n;x++){
for (int y=0; y<m; y++) {
scanf("%d",&matrix[x][y]);
}
}
int ans=0;
for(int x=0;x<n;x++){
for(int y=0;y<m;y++){
if(matrix[x][y]==1&&inq[x][y]==false){
ans++;
BFS(x,y);
}
}
}
printf("%d\n",ans);
return 0;
}
升级
#include<cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=100;
struct node{
int x,y;
int step;
}S,T,Node;
int n,m;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};//记录是否之前入队了
int X[4]={0,0,1,-1};
int Y[4]={0,0,1,-1};
bool judge(int x,int y){//判断坐标是否需要访问
if(x>=n||x<0||y>=m||y<0)
return false;
if(inq[x][y]==true)
return false;
if(matrix[x][y]=='*')
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+X[i];
int newY=top.y+Y[i];
if(judge(newX, newY)){
Node.x=newX;
Node.y=newY;
Node.step=top.step+1;
Q.push(Node);
inq[newX][newY]=true;
}
}
}
return -1;
}
int main(){
scanf("%d%d",&m,&n);
for(int x=0;x<n;x++){
getchar(); //过滤掉每行后面的换行符
for (int y=0; y<m; y++) {
matrix[x][y]=getchar();
}
matrix[x][m+1]='\0';
}
scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.ay);
S.step=0;
printf("%d\n",BFS());
return 0;
}