细胞
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:
阵列
4 10
0234500067
1034560500
2045600671
0000000089
有4个细胞
【算法分析】
⑴从文件中读入m*n矩阵阵列,将其转换为boolean矩阵存入bz数组中;
⑵沿bz数组矩阵从上到下,从左到右,找到遇到的第一个细胞;
⑶将细胞的位置入队h,并沿其上、下、左、右四个方向上的细胞位置入队,入队后的位置bz数组置为flase;
⑷将h队的队头出队,沿其上、下、左、右四个方向上的细胞位置入队,入队后的位置bz数组置为flase;
⑸重复4,直至h队空为止,则此时找出了一个细胞;
⑹重复2,直至矩阵找不到细胞;
⑺输出找到的细胞数。
#include<cstdio>
using namespace std;
int dx[4]={-1,0,1,0},
dy[4]={0,1,0,-1};
int bz[100][100],num=0,n,m;
void doit(int p,int q)
{
int x,y,t,w,i;
int h[1000][2];
num++;bz[p][q]=0;
t=0;w=1;h[1][1]=p;h[1][2]=q; //遇到的第一个细胞入队
do
{
t++; //队头指针加1
for (i=0;i<=3;i++) //沿细胞的上下左右四个方向搜索细胞
{
x=h[t][1]+dx[i];y=h[t][2]+dy[i];
if ((x>=0)&&(x<m)&&(y>=0)&&(y<n)&&(bz[x][y])) //判断该点是否可以入队
{
w++;
h[w][1]=x;
h[w][2]=y;
bz[x][y]=0;
} //本方向搜索到细胞就入队
}
}while (t<w); //直至队空为止
}
int main()
{
int i,j;
char s[100],ch;
scanf("%d%d\n",&m,&n);
for (i=0; i<=m-1;i++ )
for (j=0;j<=n-1;j++ )
bz[i][j]=1; //初始化
for (i=0;i<=m-1;i++)
{
gets(s);
for (j=0;j<=n-1;j++)
if (s[j]=='0') bz[i][j]=0;
}
for (i=0;i<=m-1;i++)
for (j=0;j<=n-1;j++)
if (bz[i][j])
doit(i,j); //在矩阵中寻找细胞
printf("NUMBER of cells=%d",num);
return 0;
}
#include <iostream>
#include <queue>
const int MAX_ROWS = 100;
const int MAX_COLS = 100;
// 定义四个方向的偏移量,用于上下左右移动
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
char grid[MAX_ROWS][MAX_COLS];
bool visited[MAX_ROWS][MAX_COLS];
// 自定义结构体来表示矩阵中的坐标
struct Coordinate {
int x;
int y;
Coordinate(int _x, int _y) : x(_x), y(_y) {}
};
// 广度优先搜索函数
void bfs(int x, int y, int rows, int cols) {
std::queue<Coordinate> q;
q.push(Coordinate(x, y));
visited[x][y] = true;
while (!q.empty()) {
Coordinate current = q.front();
q.pop();
int curX = current.x;
int curY = current.y;
for (int i = 0; i < 4; ++i) {
int newX = curX + dx[i];
int newY = curY + dy[i];
// 检查新位置是否在矩阵范围内,未被访问过,且是细胞数字(非 0)
if (newX >= 0 && newX < rows && newY >= 0 && newY < cols &&
!visited[newX][newY] && grid[newX][newY] != '0') {
q.push(Coordinate(newX, newY));
visited[newX][newY] = true;
}
}
}
}
// 计算细胞个数的函数
int countCells(int rows, int cols) {
int cellCount = 0;
// 初始化访问标记数组
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
visited[i][j] = false;
}
}
// 遍历矩阵中的每个位置
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (grid[i][j] != '0' && !visited[i][j]) {
bfs(i, j, rows, cols);
cellCount++;
}
}
}
return cellCount;
}
int main() {
int rows, cols;
// 读取矩阵的行数和列数
std::cin >> rows >> cols;
// 读取矩阵元素
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cin >> grid[i][j];
}
}
// 计算细胞个数
int result = countCells(rows, cols);
std::cout << "细胞的个数为: " << result << std::endl;
return 0;
}