洛谷 P1596 [USACO10OCT]Lake Counting S-dfs
題目描述
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.
一行:水坑的數量
輸入:
10 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.輸出:
3解題思路:
找到一個W,從這個W開始dfs,把8個方向的W都消除,然后繼續找W,計算次數。
代碼如下:
#include <iostream> using namespace std; const int N = 110; int ans;int dx[] = {0, 0, 1, -1, 1, -1, 1, -1};int dy[] = {1, -1, 0, 0, -1, -1, 1, 1}; char g[N][N]; int n, m;void dfs(int x, int y) {g[x][y] = '.';for (int i = 0; i < 8; i++) {int xx = x + dx[i], yy = y + dy[i];if (xx >= 0 && xx < n && yy >= 0 && yy < m && g[xx][yy] == 'W') {dfs(xx, yy);}} }int main() {cin >> n >> m;for (int i = 0; i < n; i++)cin >> g[i];for (int i = 0; i < n; i++)for (int j = 0; j < m; j++) {if (g[i][j] == 'W') {dfs(i, j);ans++;}}cout << ans << endl;return 0; }總結
以上是生活随笔為你收集整理的洛谷 P1596 [USACO10OCT]Lake Counting S-dfs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 炸酱面的功效与作用、禁忌和食用方法
- 下一篇: 时间与定时器操作