• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
dwtfukgv
博客园    首页    新随笔    联系   管理    订阅  订阅
CodeForces 690D1 The Wall (easy) (判断连通块的数量)

题意:给定一个图,问你有几个连通块。

析:不用说了,最简单的DFS。

代码如下:

#include <bits/stdc++.h>

using namespace std;
const int maxn = 100 + 5;
const int dr[] = {1, -1, 0, 0};
const int dc[] = {0, 0, 1, -1};
char a[maxn][maxn];
int vis[maxn][maxn];

void dfs(int r, int c){
    vis[r][c] = 1;
    for(int i = 0; i < 4; ++i){
        int x = r + dr[i];
        int y = c + dc[i];
        if(!vis[x][y] && a[x][y] == 'B')  dfs(x, y);
    }
}

int main(){
    int r, c;
    cin >> r >> c;
    getchar();
    memset(vis, 0, sizeof(vis));
    for(int i = 0; i < r; ++i)  cin >> a[i];
    int ans = 0;
    for(int i = 0; i < r; ++i)
        for(int j = 0; j < c; ++j)
            if(a[i][j] == 'B' && !vis[i][j]){
                ++ans;
                dfs(i, j);
            }
    cout << ans << endl;
    return 0;
}

 

posted on 2016-07-11 15:16  dwtfukgv  阅读(308)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3