求水窪的問題(或者是說求圖中連通子圖的個數)----深度優先算法


遇到這個題的時候,不太容易快速的想到思路;可能會比較容易想到使用遞歸的思想;
但是具體怎么寫呢?
其實這個題就相當於是圖論中的求連通圖,很容易應該想到的是深度優先搜索或者是廣度優先搜索;
我們就用深度優先算法來求這個題目;
直接求有幾個區域不好求,那么我們換個思路來求,這種題就是這樣,直接求不好求,但是當我們轉換一下思路之后就豁然開朗;

我們遍歷所有的點,當遇到有水的點時,就將它周圍的(八個方向)所有的水點都消除;所以在主遍歷for循環中遇到幾個水點就是有幾個水窪;

/*************************************************************************
	> File Name: lakeCounting.cpp
	> Author: 
	> Mail: 
	> Created Time: 2015年11月18日 星期三 21時10分13秒
 ************************************************************************/

#include<iostream>
using namespace std;

const int MAX_N = 100;
const int MAX_M = 100;

char map[MAX_N][MAX_M];
int n, m;

void input_data()
{
    cout << "input the n: ";
    cin >> n;
    cout << "input the m: ";
    cin >> m;
    cout << "input the map:" << endl;

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

void output_data()
{
    cout << "n = " << n << ", m = " << m << endl;
    for (int i = 0; i < n; ++i){
        for (int j = 0; j < m; ++j){
            cout << map[i][j];
        }
        cout << endl;
    }
    cout << endl;
}

void dfs(int x, int y)
{
    map[x][y] = '.';

    int tx, ty;

    for (int i = -1; i <= 1; ++i){
        for (int j = -1; j <= 1; ++j){
            tx = x + i;
            ty = y + j;
            if (tx >= 0 && tx < n && ty >= 0 && ty < m && map[tx][ty] == 'w'){
                dfs(tx, ty);
            }
        }
    }

    return;
}

void solve()
{
    int num = 0;

    for (int i = 0; i < n; ++i){
        for (int j = 0; j < m; ++j){
            if (map[i][j] == 'w'){
                dfs(i, j);
                num++;
            }
        }
    }

    cout << "the num is " << num << endl;
}

int main()
{
    input_data();

   //output_data();
    solve();

    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM