码迷,mamicode.com
首页 > 其他好文 > 详细

dfs:连通块

时间:2015-04-08 00:40:38      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

dfs:连通块

dfs:连通块

题目:有一个大小为N x M的园子,雨后积起了水。八连通的积水被认为是连接在一起的。清求出园子里总共有多少水洼?
(八连通指的是图中相对W的*部分),W表示积水,*表示没有积水

例如:

W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
.W.......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
输出3
#include <stdio.h>

int N;
int M;
char arr[102][102];

void dfs(int x, int y) {
    if(x < 0 || y < 0 || x >= N || y >= M || arr[x][y] == ‘.‘) {
        return;
    }

    arr[x][y] = ‘.‘;
    for(int i = -1; i <= 1; i++) {
        for(int j = -1; j <= 1; j++) {
            int nx = x + i;
            int ny = y + j;
            dfs(nx, ny);
        }
    }
}

void solve(void) {
    int ans = 0;
    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            if(arr[i][j] != ‘.‘) {
                dfs(i, j);
                ans++;
            }
        }
    }

    printf("%d\n", ans);
}

int main(void) {
    printf("input the n and m\n");
    scanf("%d%d", &N, &M);
    for(int i = 0; i < N; i++) {
        scanf("%s", arr[i]);
    }
    solve();

    return 0;
}
#include <cstdio>

const int maxn = 105;
int n;
int m;
char g[maxn][maxn];

void dfs(int x, int y) {
    g[x][y] = ‘.‘;
    for (int dx = -1; dx <= 1; dx++) {
        for (int dy = -1; dy <= 1; dy++) {
            int nx = x + dx;
            int ny = y + dy;

            if (0 <= nx && nx < n && 0 <= ny && ny < m && g[nx][ny] == ‘W‘) {
                dfs(nx, ny);
            }
        }
    }
}

void solve() {
    int res = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (g[i][j] == ‘W‘) {
                dfs(i, j);
                res++;
            }
        }
    }
    printf("%d\n", res);
}

int main(void) {

    return 0;
}
#include <cstdio>

const int maxn = 105;
bool v[maxn][maxn];
int g[maxn][maxn];
int n;
int m;

void dfs(int x, int y) {
    v[x][y] = 1;
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            int nx = x + i;
            int ny = y + j;
            if (v[nx][ny] == 0 && 0 <= nx && nx < n && 0 <= ny && ny <= m && g[nx][ny] == ‘W‘) {
                dfs(nx, ny);
            }
        }
    }
}

void solve() {
    int res = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            dfs(i, j);
            res++;
        }
    }
    printf("%d\n", res);
}

int main(void) {

    return 0;
}

dfs:连通块

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4401020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!