Description
Farmer John purchased satellite photos of W x H pixels of his farm (1 <= W <= 80, 1 <= H <= 1000) and wishes to determine the largest ‘contiguous‘ (connected) pasture. Pastures are contiguous when any pair of pixels in a pasture can be connected by traversing adjacent vertical or horizontal pixels that are part of the pasture. (It is easy to create pastures with very strange shapes, even circles that surround other circles.)
Each photo has been digitally enhanced to show pasture area as an asterisk (‘*‘) and non-pasture area as a period (‘.‘). Here is a 10 x 5 sample satellite photo:
..*.....**
.**..*****
.*...*....
..****.***
..****.***This photo shows three contiguous pastures of 4, 16, and 6 pixels. Help FJ find the largest contiguous pasture in each of his satellite photos.
Input
* Line 1: Two space-separated integers: W and H
* Lines 2..H+1: Each line contains W "*" or "." characters representing one raster line of a satellite photograph.
Output
* Line 1: The size of the largest contiguous field in the satellite photo.
Sample Input
10 5 ..*.....** .**..***** .*...*.... ..****.*** ..****.***Sample Output
16
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <string> 5 #include <algorithm> 6 7 using namespace std; 8 9 const int X[] = { 0, 0, -1, 1 }; 10 const int Y[] = { -1, 1, 0, 0 }; 11 12 const int MAX = 1010; 13 char arr[MAX][MAX]; 14 bool vis[MAX][MAX]; 15 16 int w, h; 17 int tmp, ans; 18 19 void DFS(int x, int y); 20 21 int main() 22 { 23 #ifdef OFFLINE 24 freopen("in.txt", "r", stdin); 25 freopen("out.txt", "w", stdout); 26 #endif 27 28 while (~scanf("%d%d", &w, &h)) 29 { 30 memset(arr, 0, sizeof(arr)); 31 memset(vis, false, sizeof(vis)); 32 for (int i = 0; i < h; i++) 33 scanf("%s", arr[i]); 34 35 ans = 0; 36 for (int i = 0; i < h; i++) 37 { 38 for (int j = 0; j < w; j++) 39 { 40 if (arr[i][j] == ‘*‘ && !vis[i][j]) 41 { 42 tmp = 0; 43 DFS(i, j); 44 ans = max(ans, tmp); 45 } 46 } 47 } 48 49 printf("%d\n", ans); 50 } 51 52 return 0; 53 } 54 55 void DFS(int x, int y) 56 { 57 vis[x][y] = true; 58 59 for (int i = 0; i < 4; i++) 60 { 61 int nx = x + X[i], ny = y + Y[i]; 62 if (nx >= 0 && nx < h && ny >= 0 && ny < w && arr[nx][ny] == ‘*‘ && !vis[nx][ny]) 63 { 64 DFS(nx, ny); 65 } 66 } 67 68 tmp++; 69 return; 70 }