1. 程式人生 > >洛谷 P1596 [USACO10OCT]湖計數Lake Counting 題解

洛谷 P1596 [USACO10OCT]湖計數Lake Counting 題解

for stream lin ger recent lines 輸入輸出格式 lac figure

此文為博主原創題解,轉載時請通知博主,並把原文鏈接放在正文醒目位置。

題目鏈接:https://www.luogu.org/problem/show?pid=1596

題目描述

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.

由於近期的降雨,雨水匯集在農民約翰的田地不同的地方。我們用一個NxM(1<=N<=100;1<=M<=100)網格圖表示。每個網格中有水(‘W‘) 或是旱地(‘.‘)。一個網格與其周圍的八個網格相連,而一組相連的網格視為一個水坑。約翰想弄清楚他的田地已經形成了多少水坑。給出約翰田地的示意圖,確定當中有多少水坑。

輸入輸出格式

輸入格式:

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.

第1行:兩個空格隔開的整數:N 和 M 第2行到第N+1行:每行M個字符,每個字符是‘W‘或‘.‘,它們表示網格圖中的一排。字符之間沒有空格。

輸出格式:

Line 1: The number of ponds in Farmer John‘s field.

一行:水坑的數量

輸入輸出樣例

輸入樣例#1:
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
輸出樣例#1:
3

分析:

深度優先搜索。

AC代碼:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 char mp[110][110];
 8 int m,n,ans = 0;
 9 void dfs(int x,int y)
10 {
11     mp[x][y] = .;
12         //通過將水坑標記為旱地,避免再次遍歷
13     for(int i = -1;i <= 1;i ++)
14         for(int j = -1;j <= 1;j ++)
15         {
16             int nx = x + i;
17             int ny = y + j;
18             if(nx > 0 && nx <= n && ny > 0 && ny <= m && mp[nx][ny] == W)
19                 dfs(nx,ny);
20         }
21     return;
22 }
23 
24 int main()
25 {
26     scanf("%d%d",&n,&m);
27     for(int i = 1;i <= n;i ++)
28             scanf("%s",mp[i] + 1);
29     for(int i = 1;i <= n;i ++)
30         for(int j = 1;j <= m;j ++)
31         {
32             if(mp[i][j] == W)
33                 dfs(i,j),ans ++;    
34         } 
35     printf("%d",ans);
36     return 0;
37 }

洛谷 P1596 [USACO10OCT]湖計數Lake Counting 題解