欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Lake Counting

程序员文章站 2022-07-14 20:51:15
...

题目:

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;
}
相关标签: C++ 题解