POJ1562.Oil Deposits

来源:互联网 发布:淘宝一心要几个好评 编辑:程序博客网 时间:2024/05/26 15:58

试题请参见: 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
原创粉丝点击