题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1241

题目描述

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

思路

题目要求一块田有多少块大油田?每块小油田的相邻上下左右对角线的小油田为一块大油田,即求连通分量个数。先寻找@小油田,标记为*,然后搜索其上下左右对角线,找到油田标记为*,然后搜索的次数即为大油田个数。

AC代码

/*************************************************************************
    > File Name: 1241.cpp
      > Author: Netcan
      > Blog: http://www.netcan.xyz
      > Mail: 1469709759@qq.com
      > Created Time: Sat 16 May 2015 09:48:55 PM CST
 ************************************************************************/

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <sstream>
#include <deque>
#include <functional>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <stack>
#include <set>
#include <numeric>
#include <utility>
#include <cstring>
using namespace std;

int m, n; // 田的宽m高n
char Map[105][105]; // 存放田的信息
void DFS(int i, int j) {
    if(i > m || i<1 || j>n || j<1) // 越界,回溯
        return;
    Map[i][j] = '*'; // 标记当前小油田@为*
    for(int x=-1; x<=1; ++x) // 搜索上下左右对角线
        for(int y=-1; y<=1; ++y) {
            if(Map[i+x][j+y] =='@') // 找到小油田,开始搜索
                DFS(i+x, j+y);
        }
    return;
}
int main()
{
#ifdef Oj
    freopen("1241.data", "r", stdin);
#endif
    while(cin >> m >> n && m) {
        for(int i=1; i<=m; ++i)
            for(int j=1; j<=n; ++j)
                cin >> Map[i][j];
        int counts = 0;
        for(int i=1; i<=m; ++i)
            for(int j=1; j<=n; ++j) {
                if(Map[i][j] == '@') { // 开始从第一块油田搜索
                    DFS(i, j);
                    ++counts;
                }
            }
        cout << counts << endl;
     }

    return 0;
}