<题目>:
给出一个n*m矩阵,矩阵中的元素为0或1,称位置(x,y)与其上下左右四个位置(x,y+1)(x,y-1),(x-1,y),(x+1,y)是相邻的。如果矩阵中有若干个1是相邻的(不必两两相邻)那么称这些1构成了一个“块”。求给定的矩阵中“块”的个数。如
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的矩阵中“块”的个数为4
先用DFS的递归算法实现一下!
/!!!!!我写出来啦!
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int x,y;
}Node;
const int maxn = 100;
int n,m,matrix[maxn][maxn];//大小为n*m矩阵
bool inq[maxn][maxn]={false};
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
//判断是否需要访问,矩阵下标从0开始
bool judge(int x,int y){
if(x>=n||x<0||y>=m||y<0)return false;
if(inq[x][y]==true||matrix[x][y]==0)return false;
return true;
}
void DFS(int x,int y){
inq[x][y]=true;
for(int i=0;i<4;i++){
int newX=x+X[i];
int newY=y+Y[i];
if(judge(newX,newY)) {
DFS(newX,newY);
}
//inq[newX][newY]=true;
}
return;
}
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]);
}
}
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){
ans++;
DFS(i,j);
}
}
}
printf("%d",ans);
}
/*
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
*/
再用BFS的非递归算法实现(借助队列)
//BFS用了队列的思想
#include<cstdio>
#include<queue>
using namespace std;
struct node{
int x,y;
}Node;
const int maxn = 100;
int n,m,matrix[maxn][maxn];//大小为n*m矩阵
bool inq[maxn][maxn];
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
//判断是否需要访问,矩阵下标从0开始
bool judge(int x,int y){
if(x>=n||x<0||y>=m||y<0)return false;
if(inq[x][y]==true||matrix[x][y]==0)return false;
return true;
}
//进行广度优先搜索,即只考虑搜索这一层面
void BFS(int x,int y){//从(x,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 i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d",&matrix[i][j]);
}
}
int ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(judge(i,j)){
//if(matrix[i][j]==1&&inq[i][j]==false){
ans++;
BFS(i,j);
}
}
}
printf("%d",ans);
}