给出一个 m×n 的矩阵,矩阵中的元素为 0 或 1。称位置 (x, y) 与其上、下、左、右四个位置是相邻的。如果矩阵中有若干个 1 是相邻的(不必考虑两两相邻),那么称这些 1 构成了一个“块”。求给定矩阵中“块”的个数。
Sample Input:
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
Sample Output:
4
思路:
对于矩阵 Matrix[m][n] 遍历每个元素,如果为0,则跳过;如果为 1 ,则使用BFS查询与该位置相邻的4个位置(前提是不出界),判断它们是否为 1(如果相邻的位置为1,则同样去查询与该位置相邻的4个位置,直到整个“1”块访问完毕)。为了防止走回头路,设置一个 bool型的 inq数组记录 每个元素是否已被访问过(在BFS中入队)。
技巧:
对于当前元素的下一层:上下左右,可以用增量数组访问,设置2个增量数组,来表示4个方向。
int X[] = {-1, 1, 0, 0}; // 上下左右
int Y[] = {0, 0, -1, 1};
code::
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 100; //二维数组的最大行列数
int n, m; // n:矩阵行数,m矩阵列数
int matrix[maxn][maxn];
bool inq[maxn][maxn] = {false}; // 设置所有元素为未访问过
struct node {
int x, y;
} Node; //充当临时变量,入队出队时候用
int X[4] = {-1, 1, 0,
0}; // 增量数组,该位置增加对应值就是 上、下、左、右的位置下标
int Y[4] = {0, 0, -1, 1};
bool judge(int x, int y) {
//如果越界
if (x >= n || x < 0 || y >= n || y < 0)
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 now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int newX = now.x + X[i];
int newY = now.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 i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &matrix[i][j]); // 录入矩阵的每个元素
}
}
//依次遍历矩阵的每个元素,如果为1,增加一个块,并BFS广度遍历它相邻的元素,设置为已访问过,以防其他块抢
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 1 &&
inq[i][j] == false) { // 如果这个块为1且没有被访问过
ans++;
BFS(i, j);
}
}
}
printf("%d\n", ans);
return 0;
}