• Codeforces Round #222 (Div. 1) Maze —— dfs(连通块)


    题目链接:http://codeforces.com/problemset/problem/377/A


    题解:

    有tot个空格(输入时统计),把其中k个空格变为wall,问怎么变才能使得剩下的空格依然为连通的。把问题反过来,其实就是求tot-k的连通图。dfs:在搜索过的空格中做个标记,同时更新连通个数。


    代码如下:

     1 #include<cstdio>//hdu3183 CodeForces 377A dfs
     2 #include<cstring>
     3 #include<cmath>
     4 #include<algorithm>
     5 #define LL long long
     6 
     7 using namespace std;
     8 
     9 int n,m,k,sum,vis[505][505],path[505][505];
    10 char maze[505][505];
    11 
    12 int dfs(int i, int j)
    13 {
    14     if(sum==k) return 1;
    15     if(i<1 || i>n || j<1 || j>m) return 0;
    16     if(maze[i][j]!='.' || vis[i][j]) return 0;
    17 
    18     sum++;
    19     vis[i][j] = 1;
    20     path[i][j] = 1;
    21     if(dfs(i-1,j)) return 1;
    22     if(dfs(i,j-1)) return 1;
    23     if(dfs(i+1,j)) return 1;
    24     if(dfs(i,j+1)) return 1;
    25 }
    26 
    27 int main()
    28 {
    29     scanf("%d%d%d",&n,&m,&k);
    30     k = -k;
    31     for(int i = 1; i<=n; i++)
    32     {
    33         getchar();
    34         for(int j = 1; j<=m; j++)
    35         {
    36             scanf("%c",&maze[i][j]);
    37             if(maze[i][j]=='.') k++;
    38         }
    39     }
    40 
    41     int B = 0;
    42     memset(vis,0,sizeof(vis));
    43     for(int i = 1; !B && i<=n; i++)
    44     for(int j = 1; j<=m; j++)
    45     {
    46         if(maze[i][j]=='.' && !vis[i][j])
    47         {
    48             sum = 0;
    49             memset(path,0,sizeof(path));
    50             if(dfs(i,j))
    51             {
    52                 B = 1;//双重循环,要加多个判断
    53                 break;
    54             }
    55         }
    56     }
    57 
    58     for(int i = 1; i<=n; i++)
    59     for(int j = 1; j<=m; j++)
    60     {
    61         if(maze[i][j]=='.')
    62         {
    63             if(path[i][j]) putchar('.');
    64             else putchar('X');
    65         }
    66 
    67         else putchar(maze[i][j]);
    68         if(j==m) putchar('
    ');
    69     }
    70     return 0;
    71 }
    View Code


  • 相关阅读:
    【luogu4719】动态DP模板 [动态DP]
    【2019.9.22】
    [JSOI2010]连通数[tarjan缩点]
    【2019.9.16】Za
    【2019.9.18】Za
    [USACO14OPEN]GPS的决斗Dueling GPS's [最短路]
    【CF891C】Envy [最小生成树]
    【2019.9.17】Za
    【2019.9.17】
    【luogu3403】跳楼机 [同余最短路]
  • 原文地址:https://www.cnblogs.com/DOLFAMINGO/p/7538743.html
Copyright © 2020-2023  润新知