• 洛谷P1506 拯救oibh总部 —DFS—围墙


    拯救oibh总部 - 洛谷

    ## 题目背景

    oibh 总部突然被水淹没了!现在需要你的救援……

    ## 题目描述

    oibh 被突来的洪水淹没了,还好 oibh 总部有在某些重要的地方起一些围墙。用 `*` 号表示,而一个四面被围墙围住的区域洪水是进不去的。

    oibh 总部内部也有许多重要区域,每个重要区域在图中用一个 `0` 表示。

    现在给出 oibh 的围墙建设图,问有多少个没被洪水淹到的重要区域。

    ## 输入格式

    第一行为两个正整数 $x,y$。

    接下来 $x$ 行,每行 $y$ 个整数,由 `*` 和 `0` 组成,表示 oibh 总部的建设图。

    ## 输出格式

    输出没被水淹没的 oibh 总部的 `0` 的数量。

    ## 样例 #1

    ### 样例输入 #1

    4 5
    00000
    00*00
    0*0*0
    00*00

    ### 样例输出 #1

    1

    ## 样例 #2

    ### 样例输入 #2

    5 5
    *****
    *0*0*
    **0**
    *0*0*
    *****

    ### 样例输出 #2

    5

    ## 提示

    对于 $100\%$ 的数据,$1 \le x,y \le 500$。

     分析:依次从外层向内搜索,只有全面围住的才算一个结果

    1. #include
    2. #define endl '\n'
    3. #define int long long
    4. #define Bug cout<<"---------------------"<
    5. using namespace std;
    6. constexpr int N = 550;
    7. int n, m;
    8. char mp[N][N];
    9. bool in(int x, int y) {
    10. return x >= 0 && x < n&& y >= 0 && y < m;
    11. }
    12. int dx[4] = {-1,0,0,1};
    13. int dy[4] = { 0,-1,1,0 };
    14. void dfs(int x, int y) {
    15. mp[x][y] = '*';
    16. for (int i = 0;i < 4;i++) {
    17. int tx = x + dx[i];
    18. int ty = y + dy[i];
    19. if (in(tx, ty) && mp[tx][ty] == '0') {
    20. dfs(tx, ty);
    21. }
    22. }
    23. }
    24. signed main() {
    25. ios_base::sync_with_stdio(0);
    26. cin.tie(0); cout.tie(0);
    27. cin >> n >> m;
    28. for (int i = 0;i < n;i++) {
    29. for (int j = 0;j < m;j++) {
    30. cin >> mp[i][j];
    31. if (mp[i][j] == 0) {
    32. mp[i][j] = '0';
    33. }
    34. }
    35. }
    36. //搜索第一行和最后一行;
    37. for (int i = 0;i < m;i++) {
    38. if (mp[0][i]=='0') {
    39. dfs(0, i);
    40. }
    41. if (mp[n - 1][i] == '0') {
    42. dfs(n - 1, i);
    43. }
    44. }
    45. //搜索第一列,最后一列
    46. for (int i = 0;i < n;i++) {
    47. if (mp[i][0]=='0') {
    48. dfs(i, 0);
    49. }
    50. if (mp[i][m - 1] == '0') {
    51. dfs(i, m - 1);
    52. }
    53. }
    54. int ans = 0;
    55. for (int i = 0;i < n;i++) {
    56. for (int j = 0;j < m;j++) {
    57. if (mp[i][j]=='0') {
    58. ans++;
    59. }
    60. }
    61. }
    62. cout << ans << endl;
    63. return 0;
    64. }

  • 相关阅读:
    人脸识别数据库,RGB和IR都有
    格拉姆角场GAF将时序数据转换为图像并应用于东南大学轴承故障诊断(Python代码,CNN模型)
    驱动DAY9
    MySQL忘记密码后重置密码(windows版本)
    【网络编程】Linux网络编程基础与实战第一弹——网络基础
    信息化发展52
    数据结构与算法之字典: Leetcode 349. 两个数组的交集 (Typescript版)
    LeetCode--快速排序
    Spring Security 登录获取用户信息流程分析
    java 20 Stream流
  • 原文地址:https://blog.csdn.net/m0_72522122/article/details/127666009