问题:求一个矩阵的的块数
1101 //这矩阵块数是3
0100
0011
1.小技巧,增量数组X[],Y[],可以用来表示增加上下左右的位置,命名要注意
2.BFS()是将一个位置周围都是1的数都加入队列,避免重复访问
3.数组下标从0开始,故要注意越界的情况
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 20;
int n,m; //n*m数组
int matrix[maxn][maxn] ;
bool inq[maxn][maxn] = {false}; //是否进入过队列
int X[4] = {0,1,0,-1}; //命名要大写,不要与x混淆
int Y[4] = {1,0,-1,0};
struct node{ //位置节点
int x,y;
}Node;
bool judge(int x, int y){
if(x<0||y<0|| x>=n|| y>=m) return false; //位置越界则不访问
//矩阵值为0或者已经在队列了,也不访问
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.top()
Q.pop();
for(int i=0; i<4; i++){ //循环4次,得到4个相邻位置
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); //n*m矩阵
for(int x=0; x<n; x++){
for(int y=0; y<m; y++){
scanf("%d" , &matrix[x][y]); //初始化矩阵
}
}
int block_n = 0;
for(int x=0; x<n; x++){
for(int y=0; y<m; y++){
if(matrix[x][y] == 1 && inq[x][y] == false){ //为1,且不在队列中,记块数+1
block_n++;
BFS(x,y); //找出相邻的所有1,并将其入队列
}
}
}
printf("%d",block_n);
return 0;
}