Lake Counting
题目:
Description
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.
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.
Output -
Line 1: The number of ponds in Farmer John’s field.
良心翻译:
描述
由于最近的降雨,水汇集在Farmer John’s田地的不同地方,其由N×M(1 <= N <= 100; 1 <= M <= 100)的正方形矩形表示。每个方块包含水(‘W’)或旱地(’.’)。农夫约翰想弄清楚他的田地里有多少个池塘。池塘是一组连接的正方形,其中有水,其中一个正方形被认为与其所有八个邻居相邻。
给出农夫约翰的田地图,确定他有多少池塘。
输入
*第1行:两个以空格分隔的整数:N和M.
*行2…N + 1:每行M个字符代表一行Farmer John的字段。每个字符都是’W’或’.’。字符之间没有空格。
产量
*第1行:Farmer John的田地里的池塘数量。
思路:
题目一大段,只是让你做一件事情:数连通块,DFS一波就行了。
代码:
#include<bits/stdc++.h>
using namespace std;
int n,m;
int maze[1010][1010];
bool vis[1010][1010];
bool in(int x,int y){
return x>=1&&x<=n&&y>=1&&y<=m;
}//防止出界
int dir[8][2]={{1,0},{-1,0},{0,1},{0,-1},{-1,-1},{1,1},{-1,1},{1,-1}};//八个方向
void dfs(int sx,int sy){
vis[sx][sy]=1;//标记起点
for(int i=0;i<8;i++){
int tx=sx+dir[i][0];
int ty=sy+dir[i][1];
if(!vis[tx][ty] && maze[tx][ty]==1&&in(tx,ty)){
dfs(tx,ty);/继续dfs
}
}
return;
}
int main(){
int ans=0;
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
char pi;
cin>>pi;
if(pi=='W'){
maze[i][j]=1;
}else{
maze[i][j]=0;
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(maze[i][j]==1 && !vis[i][j]){
dfs(i,j);
ans++;//枚举点,dfs它后,和他联通的块就被标记了,答案数+1
}
}
}
cout<<ans;
return 0;
}
上一篇: Android 实现监听事件的几种方法
下一篇: thinkphp 实战记录 3
推荐阅读
-
MacBook Pro搭载具体哪款Kaby Lake处理器?
-
1004 Counting Leaves (30 分)(树的遍历)
-
Intel Alder Lake-S桌面CPU浮现:10nm++工艺、LGA1700接口
-
MacBook Pro搭载具体哪款Kaby Lake处理器?
-
Intel 10nm++工艺终于传来喜讯 45W Tiger Lake-H内测中
-
Kaby Lake-X怎么样?Kaby Lake-X i7-7740X/i5-7640X深度评测
-
8代酷睿Coffee Lake首测 Intel i5 8250U移动CPU处理器性能对比评测
-
Intel即将揭秘第11代核显:10nm Ice Lake年底见
-
Intel Comet Lake家族酷睿i3-10100桌面处理器现身:首次4核8线程
-
Intel:10nm的Ice Lake处理器相比前代有18% IPC提升