题目:
在m*n矩阵中找出块的个数(块“相邻为1的点组合而成)
1 1 0 0
0 0 1 1
1 0 0 1
则相邻整体块数为 3
BFS实现:
#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>
#include <cmath>
using namespace std;
const int maxn = 1000;
struct node
{
int x,y;
}Node;
int m,n;
int X[4] = {-1,0,0,1};
int Y[4] = {0,1,-1,0};
int d[maxn][maxn];//用于存放迷宫数据
bool inq[maxn][maxn] ={false};
bool judge(int x,int y)
{
//越界
if(x > m || x < 0 || y < 0 || y > n) return false;
//d[x][y]是0 或者是已经被访问过了
if(d[x][y]==0 || inq[x][y] == true) return false;
else return true;
}
void BFS(int x,int y)
{
queue<node> q; //定义队列
Node.x = x,Node.y = y;//当前节点(x,y)
q.push(Node);//节点入队列
inq[x][y] = true;//入队标记
while(!q.empty())
{
node top =q.front(); //取出队首
q.pop(); //弹出当前节点
for(int i = 0; i < 4; i++) //循环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()
{
cin >> m >> n;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
cin >> d[i][j];
}
}
int cont = 0;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(d[i][j] != 0 && !inq[i][j])
{
BFS(i,j);
cont++;
}
}
}
cout << cont;
return 0;
}