求连通块的数量(dfs、bfs)

文章提供了两个Java程序,分别实现了广度优先搜索(BFS)和深度优先搜索(DFS)算法。这两个算法常用于图的遍历。BFS程序计算从起点开始能走到的所有崭新黑瓷砖的数量,而DFS程序则标记并计数从起点开始的所有路径。

AC代码:
1、bfs

import javax.swing.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.file.attribute.AclEntryFlag;
import java.security.AlgorithmConstraints;
import java.sql.Struct;
import java.text.CollationElementIterator;
import java.text.DateFormatSymbols;
import java.util.*;
import java.util.stream.Collectors;


public class Main
{
    static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    static int N = (int)0 + 20;
    static math_myself math_me = new math_myself();
    static char g[][] = new char[N][N];
    static boolean used[][] = new boolean[N][N];
    static int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
    static Queue<PII> q = new LinkedList<>();

    static int n,m;

    static int bfs(int x, int y)
    {
        q.add(new PII(x,y));
        used[x][y] = true;
        int cnt = 1; // 起点就是黑色砖块,也要算进去

        while(q.size() > 0)
        {
            PII t = q.poll();

            for(int i = 0 ; i < 4 ; i ++)
            {
                int x_cur = t.x + dx[i],y_cur = t.y + dy[i];
                if(x_cur < 0 || x_cur >= n || y_cur < 0 || y_cur >= m)  continue; // 越界不走
                if (used[x_cur][y_cur])  continue; // 走过的瓷砖不走
                if (g[x_cur][y_cur] != '.')  continue; // 不是崭新的黑瓷砖不走

                // 崭新的黑瓷砖必然是可以走的
                used[x_cur][y_cur] = true;
                q.add(new PII(x_cur,y_cur));
                cnt ++;
            }
        }
        return cnt;
    }

    public static void main(String[] args ) throws IOException
    {
        while(true)
        {
            q.clear();
            for(int i = 0 ; i < n; i ++)  Arrays.fill(used[i],false);
            // 正常是先输入n,再输入m,这题反着
            m = rd.nextInt();
            n = rd.nextInt();

            if (m == 0 || n == 0) break;
            // 读入矩阵
            for(int i = 0 ; i < n ; i ++)  g[i] = rd.next().toCharArray();

            // 寻找起点
            int x = 0,y = 0,flag = 0;
            for(int i = 0 ; i < n ; i ++)
            {
                for(int j = 0 ; j < m ; j ++)
                {
                    if(g[i][j] == '@')
                    {
                        x = i;
                        y = j;
                        flag = 1;
                    }
                    if (flag == 1)  break;
                }
            }

            pw.println(bfs(x,y));
        }
        pw.flush();
    }
}

class rd
{
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tokenizer = new StringTokenizer("");

    static String nextLine() throws IOException   { return reader.readLine(); }

    static String next() throws IOException
    {
        while (!tokenizer.hasMoreTokens())  tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException  { return Integer.parseInt(next()); }

    static double nextDouble() throws IOException { return Double.parseDouble(next()); }

    static long nextLong() throws IOException  { return Long.parseLong(next());}

    static BigInteger nextBigInteger() throws IOException
    {
        BigInteger d = new BigInteger(rd.nextLine());
        return d;
    }
}

class PII
{
    int x,y;
    public PII(int x ,int y)
    {
        this.x = x;
        this.y = y;
    }
}

class math_myself
{
    int gcd(int a,int b)
    {
        if(b == 0)  return a;
        else return gcd(b,a % b);
    }

    int lcm(int a,int b)
    {
        return a * b / gcd(a, b);
    }

    // 求n的所有约数
    List get_factor(int n)
    {
        List<Long> a = new ArrayList<>();
        for(long i = 1; i <= Math.sqrt(n) ; i ++)
        {
            if(n % i == 0)
            {
                a.add(i);
                if(i != n / i)  a.add(n / i);  // // 避免一下的情况:x = 16时,i = 4 ,x / i = 4的情况,这样会加入两种情况  ^-^复杂度能减少多少是多少
            }
        }

        // 相同因子去重,这个方法,完美
        a = a.stream().distinct().collect(Collectors.toList());

        // 对因子排序(升序)
        Collections.sort(a);

        return a;
    }

    // 判断是否是质数
    boolean check_isPrime(int n)
    {
        if(n < 2) return false;
        for(int i = 2 ; i <= n / i; i ++)  if (n % i == 0) return false;
        return true;
    }
}

2、dfs

import javax.swing.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.file.attribute.AclEntryFlag;
import java.security.AlgorithmConstraints;
import java.sql.Struct;
import java.text.CollationElementIterator;
import java.text.DateFormatSymbols;
import java.util.*;
import java.util.stream.Collectors;


public class Main
{
    static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    static int N = (int)0 + 20;
    static math_myself math_me = new math_myself();
    static char g[][] = new char[N][N];
    static int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
    static int n,m;
    static int cnt;

    // 只有崭新的黑色瓷砖才会进dfs
    static void dfs(int x, int y)
    {
        g[x][y] = '#'; // 走过的点变成红色瓷砖,以免重复走
        cnt ++; // 走过的黑色的
        for(int i = 0 ; i < 4 ; i ++)
        {
            int x_cur = x + dx[i],y_cur = y + dy[i];
            if(x_cur < 0 || x_cur >= n || y_cur < 0 || y_cur >= m || g[x_cur][y_cur] == '#')  continue;  // 红色的瓷砖或者走过的黑瓷砖(变成红色瓷砖)不会进dfs
            dfs(x_cur,y_cur);
        }
    }

    public static void main(String[] args ) throws IOException
    {
        while(true)
        {
            cnt = 0;
            // 正常是先输入n,再输入m,这题反着
            m = rd.nextInt();
            n = rd.nextInt();

            if (m == 0 || n == 0) break;
            // 读入矩阵
            for(int i = 0 ; i < n ; i ++)  g[i] = rd.next().toCharArray();

            // 寻找起点
            int x = 0,y = 0,flag = 0;
            for(int i = 0 ; i < n ; i ++)
            {
                for(int j = 0 ; j < m ; j ++)
                {
                    if(g[i][j] == '@')
                    {
                        x = i;
                        y = j;
                        flag = 1;
                    }
                    if (flag == 1)  break;
                }
            }

            dfs(x,y); // 传入起点

            pw.println(cnt);
        }
        pw.flush();
    }
}

class rd
{
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tokenizer = new StringTokenizer("");

    static String nextLine() throws IOException   { return reader.readLine(); }

    static String next() throws IOException
    {
        while (!tokenizer.hasMoreTokens())  tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException  { return Integer.parseInt(next()); }

    static double nextDouble() throws IOException { return Double.parseDouble(next()); }

    static long nextLong() throws IOException  { return Long.parseLong(next());}

    static BigInteger nextBigInteger() throws IOException
    {
        BigInteger d = new BigInteger(rd.nextLine());
        return d;
    }
}

class PII
{
    int x,y;
    public PII(int x ,int y)
    {
        this.x = x;
        this.y = y;
    }
}

class math_myself
{
    int gcd(int a,int b)
    {
        if(b == 0)  return a;
        else return gcd(b,a % b);
    }

    int lcm(int a,int b)
    {
        return a * b / gcd(a, b);
    }

    // 求n的所有约数
    List get_factor(int n)
    {
        List<Long> a = new ArrayList<>();
        for(long i = 1; i <= Math.sqrt(n) ; i ++)
        {
            if(n % i == 0)
            {
                a.add(i);
                if(i != n / i)  a.add(n / i);  // // 避免一下的情况:x = 16时,i = 4 ,x / i = 4的情况,这样会加入两种情况  ^-^复杂度能减少多少是多少
            }
        }

        // 相同因子去重,这个方法,完美
        a = a.stream().distinct().collect(Collectors.toList());

        // 对因子排序(升序)
        Collections.sort(a);

        return a;
    }

    // 判断是否是质数
    boolean check_isPrime(int n)
    {
        if(n < 2) return false;
        for(int i = 2 ; i <= n / i; i ++)  if (n % i == 0) return false;
        return true;
    }
}

### 蓝桥杯 DFSBFS 的真题题目及解析 #### 题目一:剪邮票 (DFS 枚举组合情况 + BFS 判断连通性) 此题来源于蓝桥杯历年的经典题目之一——剪邮票问题。该问题的核心在于通过 **DFS** 来枚举可能的解空间,并利用 **BFS** 判断剩余部分是否仍然保持连通性。 ##### 问题描述 给定一张由若干个相连的小正方形组成的矩形纸片,表示一片完整的邮票区域。每次可以从这片区域内移除一个小正方形,问是否存在一种方式使得最终剩下的部分仍然是连通的一整。 ##### 解析 为了实现这一目标,可以通过以下方法解决: 1. 使用 **DFS** 对所有可能的删除顺序进行穷举。 2. 在每一次删除操作之后,调用 **BFS** 或并查集来判断当前剩余的部分是否依然构成单一连通块[^1]。 以下是基于 C++ 实现的一个简单框架: ```cpp #include <iostream> #include <queue> using namespace std; const int MAX_N = 10; bool grid[MAX_N][MAX_N]; int n, m; // BFS 函数用于检测连通性 bool bfs(int sx, int sy) { queue<pair<int, int>> q; bool visited[MAX_N][MAX_N] = {false}; q.push({sx, sy}); visited[sx][sy] = true; int count = 0; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); ++count; static const int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; for (int i = 0; i < 4; ++i) { int nx = x + dx[i], ny = y + dy[i]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny] && grid[nx][ny]) { visited[nx][ny] = true; q.push({nx, ny}); } } } // 如果遍历到的所有格子数量等于总有效格子数,则说明连通 return count == n * m; } void dfs(int step) { if (step == n * m) { // 检测最后状态是否满足条件 for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] && bfs(i, j)) { cout << "存在合法方案" << endl; return; } } } return; } // 尝试保留当前位置或者将其移除 int r = step / m, c = step % m; if (grid[r][c]) { // 移除这个位置 grid[r][c] = false; dfs(step + 1); grid[r][c] = true; // 不移除此位置 dfs(step + 1); } else { dfs(step + 1); } } ``` --- #### 题目二:独立海域 (BFS 应用实例) 本题是一个典型的 **BFS** 应用场景,涉及如何在一个二维网格中找到未被污染的孤立区。 ##### 问题描述 给定一个大小为 \(n \times m\) 的矩阵,其中某些单元格已经被标记为受污染的状态(例如 'X'),而其他单元格则处于正常状态(例如 '.')。如果某个正常的单元格周围全部都是污染区,则认为它是一完全隔离的安全区域。这样的安全区域的数量。 ##### 解析 针对这个问题,可以采用如下策略: 1. 初始化一个布尔数组 `vis` 记录哪些节点已经访问过。 2. 遍历整个地图,当遇到尚未访问过的正常单元格时启动一次 **BFS** 探索其周围的环境。 3. 若发现某次探索的结果表明该单元格四周均为污染区,则计数器加一[^4]。 下面是 Python 版本的具体实现代码: ```python from collections import deque def is_isolated(x, y, grid, vis): directions = [(0, 1), (1, 0), (-1, 0), (0, -1)] n, m = len(grid), len(grid[0]) # 边界外默认视为污染区 for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] != 'X': return False return True def count_safe_areas(grid): n, m = len(grid), len(grid[0]) vis = [[False]*m for _ in range(n)] safe_count = 0 for i in range(n): for j in range(m): if not vis[i][j] and grid[i][j] == '.': if is_isolated(i, j, grid, vis): safe_count += 1 # 启动 BFS 扩散标记已访问区域 q = deque([(i, j)]) while q: cx, cy = q.popleft() if vis[cx][cy]: continue vis[cx][cy] = True for dx, dy in ((0, 1), (1, 0), (-1, 0), (0, -1)): nx, ny = cx + dx, cy + dy if 0 <= nx < n and 0 <= ny < m and not vis[nx][ny] and grid[nx][ny] == '.': q.append((nx, ny)) return safe_count # 测试样例 if __name__ == "__main__": grid = [ ['.', '.', 'X', '.'], ['X', '.', 'X', 'X'], ['.', '.', '.', 'X'] ] result = count_safe_areas(grid) print(f"共有 {result} 独立安全区域") ``` --- #### 总结 上述两道题目分别展示了 **DFS** 和 **BFS** 在实际竞赛中的应用形式。前者侧重于复杂状态的空间搜索以及连通性的验证;后者更关注局部范围内的可达性和边界判定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

21RGHLY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值