其他分享
首页 > 其他分享> > poj2386:Lake Counting

poj2386:Lake Counting

作者:互联网

给定一个图,'.'表示陆地,'W'表示有水,求水洼的数量

image-20220211084223953

遍历图,若遍历到'W'则进行深搜,将该点置为'.',遍历该点所有邻接点,若为'W'则继续深搜

在遍历图的过程中进行调用dfs的次数即为水洼数(怎么感觉像求连通分量......)

#include<stdio.h>
#include<iostream>
using namespace std;

const int MAXSIZE = 100 + 10;
char filed[MAXSIZE][MAXSIZE];
int n, m;

void dfs(int x, int y){
    filed[x][y] = '.';  //将(x,y)置为 '.'
    //遍历8个方向
    for(int dx = -1; dx <= 1; ++dx){
        for(int dy = -1; dy <= 1; ++dy){
            //(nx,ny)为下一个邻接点
            int nx = x + dx;
            int ny = y + dy;
            //判定邻接点是否在范围内 且 如果是'W'则深搜
            if( (nx >= 0 && nx < n) && (ny >= 0 && ny < m) && filed[nx][ny] == 'W'){
                dfs(nx, ny);
            }
        }
    }
}

int main(){

    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; ++i){
        getchar();
        for(int j = 0; j < m; ++j){
            scanf("%c", &filed[i][j]);
        }
    }

    int answer = 0;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            if(filed[i][j] == 'W'){
                dfs(i, j);
                ++answer;   //总共进行深搜的次数即为所求
            }
        }
    }
    printf("%d\n", answer);
    return 0;
}

标签:遍历,ny,int,Lake,++,&&,filed,Counting,poj2386
来源: https://www.cnblogs.com/dctwan/p/15881782.html