输入:
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
输出:
4
vector存储版
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int maxn=30,maxm=30;
bool s[maxn][maxm]={false};
int m,n;
queue<int>qh,ql;
void BFS(vector<int> *v,int x,int y){
qh.push(x);ql.push(y);
s[x][y]=true;
while(!ql.empty()){
int nx=qh.front(),ny=ql.front();
qh.pop();ql.pop();
for(int i=-1;i<2;i++)
for(int j=-1;j<2;j++){
if(abs(i)!=abs(j)&&nx+i>=0&&ny+j>=0&&nx+i<m&&ny+j<n&&!s[nx+i][ny+j]&&v[nx+i][ny+j]!=0){
qh.push(nx+i);ql.push(ny+j);
s[nx+i][ny+j]=true;
}
}
}
}
int main(){
int ans=0,tem;
cin>>m>>n;
vector<int>v[m];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
cin>>tem;
v[i].push_back(tem);
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(v[i][j]!=0&&!s[i][j]){
ans++;
BFS(v,i,j);
}
}
}
cout<<ans;
return 0;
}
算法笔记上的版本
#include<iostream>
#include<queue>
using namespace std;
struct node{
int x,y;
}Node;
const int maxn=100;
int n,m;
int matrix[maxn][maxn];
bool inq[maxn][maxn]={false};
int X[4]={0,0,1,-1},Y[4]={1,-1,0,0};
bool judge(int x,int y){
if(x>=n||x<0||y>=m||y<0) return false;
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.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(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>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++;
BFS(i,j);
}
}
}
cout<<ans;
return 0;
}
注:是上下左右四个位置而不是九个位置,在使用队列时,我错误的在while循环中使用递归,这是思想没有明确的原因,没有明确在BFS函数中到底要完成什么,BFS函数是为了完成一个块的判定而非一个个点的判定,在main函数中的for循环才是点的判断