![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <stack> #define Max 101 using namespace std; char mp[Max][Max]; int n,m,vis[Max][Max],c; int dir[8][2] = {0,1,1,0,0,-1,-1,0,1,1,1,-1,-1,1,-1,-1}; void dfs(int x,int y) { for(int i = 0;i < 8;i ++) { int tx = x + dir[i][0]; int ty = y + dir[i][1]; if(tx < 0 || ty < 0 || tx >= n || ty >= m || mp[tx][ty] == '.' || vis[tx][ty])continue; vis[tx][ty] = 1; dfs(tx,ty); } } int main() { cin>>n>>m; for(int i = 0;i < n;i ++) cin>>mp[i]; for(int i = 0;i < n;i ++) { for(int j = 0;j < m;j ++) { if(mp[i][j] == 'W' && vis[i][j] == 0) { vis[i][j] = 1; dfs(i,j); c ++; } } } cout<<c<<endl; }
Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John's field, determine how many ponds he has.
Given a diagram of Farmer John's field, determine how many ponds he has.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.
* Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.
Output
* Line 1: The number of ponds in Farmer John's field.
Sample Input
10 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.
Sample Output
3
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
Source
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 42151 | Accepted: 20899 |
如果觉得有帮助,点个推荐啦~
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步