dfs

Leyni是一个地址调查员,有一天在他调查的地方突然出现个泉眼。由于当地的地势不均匀,有高有低,他觉得如果这个泉眼不断的向外溶出水来,这意味着这里在不久的将来将会一个小湖。水往低处流,凡是比泉眼地势低或者等于的地方都会被水淹没,地势高的地方水不会越过。而且又因为泉水比较弱,当所有地势低的地方被淹没后,水位将不会上涨,一直定在跟泉眼一样的水位上。
   由于Leyni已经调查过当地很久了,所以他手中有这里地势的详细数据。所有的地图都是一个矩形,并按照坐标系分成了一个个小方格,Leyni知道每个方格的具体高度。我们假定当水留到地图边界时,不会留出地图外,现在他想通过这些数据分析出,将来这里将会出现一个多大面积的湖。

有若干组数据,每组数据的第一行有四个整数n,m,p1,p2(0<n,m,p1,p2<=1000),n和m表示当前地图的长和宽,p1和p2表示当前地图的泉眼位置,即第p1行第p2列,随后的n行中,每行有m个数据。表示这每一个对应坐标的高度。

输出对应地图中会有多少个格子被水充满。

3 5 2 3
3 4 1 5 1
2 3 3 4 7
4 1 4 1 1

6

问题分析 :

  一个dfs 的标准模板题, 对于每个点 , 遍历四个方向 。

代码示例 :

  

/*
 * Author:  ry 
 * Created Time:  2017/9/19 14:52:38
 * File Name: 1.cpp
 */
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <time.h>
using namespace std;
const int mm = 1e6+5;
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define ll long long

int ans = 0;
int n, m, p1, p2;
int map[1005][1005];
bool vis[1005][1005];
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};

bool check(int x, int y){
    if(!vis[x][y] && x >= 1 && x <= n && y >= 1 && y <= m){
        return true;
    }
    else return false;
}

void dfs(int x, int y){
    vis[x][y] = true;
    if (map[x][y] > map[p1][p2]) return;
    ans++;
    for(int i = 0; i < 4; i++){
        if(check(x+dir[i][0], y+dir[i][1])){
            dfs(x+dir[i][0], y+dir[i][1]);
        }
    }
}

int main() {
    
    while (~scanf("%d%d%d%d", &n, &m, &p1, &p2)){
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m; j++){
                scanf("%d", &map[i][j]);
            }
        }
        memset(vis, 0, sizeof(vis));
        ans = 0;
        dfs(p1, p2);
        
        printf("%d
", ans);
    }

    return 0;
}
东北日出西边雨 道是无情却有情
原文地址:https://www.cnblogs.com/ccut-ry/p/7552068.html