POJ1562.Oil Deposits

试题请参见: http://poj.org/problem?id=1562

题目概述

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.

解题思路

简单的深度优先搜索.
当遍历一个节点时, 搜索剩下8个方向的节点, 并将它们全部填充为*(没有油田), 同时将计数器+1. 直至遍历完全部节点.

源代码

#include <iostream>

const int MAX_SIZE = 100;

char map[MAX_SIZE][MAX_SIZE] = {0};

/**
 * 搜索邻近的油田.
 * @param i - 当前的纵坐标
 * @param j - 当前的横坐标
 * @param m - 纵坐标最大值
 * @param n - 横坐标最大值
 */
void searchAdjacentDeposits(int i, int j, int m, int n) {
    if ( map[i][j] != '@' || i < 0 || j < 0 || i >= m || j >= n ) {
        return;
    }

    // 将已访问的点置为*
    map[i][j] = '*';

    // 搜索邻近的点
    searchAdjacentDeposits(i - 1, j - 1, m, n);
    searchAdjacentDeposits(i - 1, j, m, n);
    searchAdjacentDeposits(i - 1, j + 1, m, n);
    searchAdjacentDeposits(i, j - 1, m, n);
    searchAdjacentDeposits(i, j + 1, m, n);
    searchAdjacentDeposits(i + 1, j - 1, m, n);
    searchAdjacentDeposits(i + 1, j, m, n);
    searchAdjacentDeposits(i + 1, j + 1, m, n);
}

int main() {
    int m = 0, n = 0;

    while ( std::cin >> m >> n ) {
        if ( m == 0 ) {
            break;
        }

        int numberOfDeposits = 0;
        for ( int i = 0; i < m; ++ i ) {
            for ( int j = 0; j < n; ++ j ) {
                std::cin >> map[i][j];
            }
        }

        for ( int i = 0; i < m; ++ i ) {
            for ( int j = 0; j < n; ++ j ) {
                if ( map[i][j] == '@' ) {
                    searchAdjacentDeposits(i, j, m, n);
                    ++ numberOfDeposits;
                }
            }
        }
        std::cout << numberOfDeposits << std::endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值