DFS questions
Original question link: http://poj.org/problem? Id = 3620
My link: http://acm.hust.edu.cn/vjudge/contest/view.action? Cid = 19651 # Problem/B
Avoid the lakes
Time limit:1000 ms |
|
Memory limit:65536 K |
Total submissions:5563 |
|
Accepted:2995 |
Description
Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of water. his insurance agency will only repay him, however, an amount depending on the size of the largest "Lake" on his
Farm.
The farm is represented as a rectangular gridN(1 ≤N≤ 100) rows andM(1 ≤M≤ 100) columns. Each cell in the grid is either dry or submerged, and exactlyK(1 ≤K≤N×M) Of
Cells are submerged. as one wowould perform CT, a lake has a central cell to which other cells connect by sharing a long edge (not a corner ). any cell that shares a long edge with the central cell or shares a long edge with any connected cell becomes a connected
Cell and is part of the lake.
Input
* Line 1: three space-separated integers:N,M, AndK
* Lines 2 ..K+ 1: LineI+ 1 describes one submerged location with two space separated integers that are its row and column:RAndC
Output
* Line 1: the number of cells that the largest lake contains.
Sample Input
3 4 53 22 23 12 31 1
Sample output
4
Source
Usaco 2007 November Bronze
At the beginning, I did not understand the meaning of the DFS questions. orz should be a trainer.
A matrix is provided. Some of the grids are dry and wet.
If a damp grid is wet in four adjacent directions, they can form a larger grid.
The largest lake.
That is, to find the maximum number of wet grids connected together.
// 288 kb16 MSC ++ 874 B2013-03-02 18:52:46 # include <cstdio> # include <cstring> const int maxn = 110; bool map [maxn] [maxn]; // record the moisture point int dir [4] [2] = {, 0,-1,-,}; // int n, m, K in the direction; int sum, result; void DFS (int x, int y) {sum ++; If (! Map [x] [Y]) return; // exit map [x] [Y] = false if it is not wet on this side; // also mark for (INT I = 0; I <4; I ++) {int next_x = x + dir [I] [0]; int next_y = Y + dir [I] [1]; if (next_x> = 1 & next_x <= N & next_y> = 1 & next_y <= M & map [next_x] [next_y]) DFS (next_x, next_y) ;}} int main () {While (scanf ("% d", & N, & M, & K )! = EOF) {result = 0; memset (MAP, false, sizeof (MAP); For (INT I = 1; I <= K; I ++) {int X, y; scanf ("% d", & X, & Y); map [x] [Y] = true ;}for (INT I = 1; I <= N; I ++) {for (Int J = 1; j <= m; j ++) {If (Map [I] [J]) {sum = 0; DFS (I, j); Result = Result> sum? Result: sum ;}} printf ("% d \ n", result) ;}return 0 ;}