ACM-Satellite Photographs

题目描述:Satellite Photographs

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.

输入

* 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.

输出

* Line 1: The size of the largest contiguous field in the satellite photo.

样例输入

10 5
..*.....**
.**..*****
.*...*....
..****.***
..****.***

样例输出

16

思路:DFS求最大相连区域,8个方向

 1 // Satellite Photographs.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 
 6 #include <iostream>
 7 #include <cstring>
 8 #include <algorithm>
 9 using namespace std;
10 
11 const int MAX = 1005;
12 int n, m,ans, vis[MAX][MAX], dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1};
13 char map[MAX][MAX];
14 
15 void DFS(int x, int y, int num)
16 {
17     //cout << "x:" << x << "	y:" << y << "	num:" << num << endl;
18     ans = max(ans, num);
19     
20     for (int i = 0; i < 4; i++)
21     {
22         int nx = x + dir[i][0];
23         int ny = y + dir[i][1];
24         if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && map[nx][ny] == '*')
25         {
26             //cout << "nx:" << nx << "	ny:" << ny << endl;
27             vis[nx][ny] = 1;
28             DFS(nx, ny, num + 1);
29             vis[nx][ny] = 0;
30         }
31     }
32 
33 
34 }
35 
36 
37 int main()
38 {
39 
40         memset(vis, 0, sizeof(vis));
41         memset(map, '', sizeof(map));
42         ans = 0;
43 
44         cin >> m >> n ;
45         for (int i = 0; i < n; i++)
46             cin >> map[i];
47 
48         for (int i = 0; i < n; i++)
49         {
50             for (int j = 0; j < m; j++)
51             {
52                 if (map[i][j] == '*' && !vis[i][j])
53                 {
54                     vis[i][j] = 1;
55                     DFS(i, j, 1);
56                     vis[i][j] = 0;
57                 }
58 
59             }
60         }
61         cout << ans << endl;
62 
63 
64 }



 
 
原文地址:https://www.cnblogs.com/x739400043/p/8505380.html