图论
1.bfs
输入
4 10
0234500067
1034560500
2045600671
0000000089
(四行十列)
四连通
1~9之间可相互连通,0是障碍
#include<iostream> #include<cstdio> #include<algorithm> #define go(i,a,b) for(int i=a;i<=b;++i) #define pii pair<int,int> using namespace std; const int N=110,M=N*N; char s[110][110]; pii q[M]; bool st[N][N]; int n,m; int dx[]={ 0, 0,+1,-1}; int dy[]={+1,-1, 0, 0}; void bfs(int x,int y){ int hh=0,tt=0; q[0]={x,y}; st[x][y]=true; while(hh<=tt){ go(i,0,3){ int xx=q[hh].first+dx[i],yy=q[hh].second+dy[i]; if(xx<0||xx>n-1||yy<0||yy>m-1)continue; if(s[xx][yy]=='0'||st[xx][yy])continue; q[++tt]={xx,yy}; st[xx][yy]=true; } ++hh; } } int main(){ cin>>n>>m; go(i,0,n-1) scanf("%s",s[i]); int ans=0; go(i,0,n-1) go(j,0,m-1){ if(s[i][j]!='0'&&!st[i][j]){ bfs(i,j); ++ans; } } cout<<ans; return 0; }