CF377A Maze题解

博客介绍了CF377A Maze问题的解决方案,题目要求在现有地图上添置k堵墙,保持空地为一个连通块。作者采用逆向思维,先将所有空地标记为墙,然后找出大小为ans-k的连通块。解题方法涉及深度优先搜索(DFS)并注意计数器的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CF377A Maze

题意:有一个地图,有空地和墙,空地是一个连通块,问要再添k堵墙,使得空地还是一个连通块,输出改变后的地图。
解法:这题的思维很新颖,没想到啊,如果正面搜索,需要考虑的情况比较多,所以逆向思维,先把所有’.‘变成’X’,然后,再找出一个大小为ans-k数量的连通块,记得dfs的时候计数器要定义为全局变量,害,下次我还写bfs。
代码

#include  <algorithm>
#include  <iostream>
#include  <cstring>
#include  <vector>
#include  <cstdio>
#include  <queue>
#include  <cmath>
#include  <set>
#include  <map>
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define _for(n,m,i) for (register int i = (n); i < (m); ++i)
#define _rep(n,m,i) for (register int i = (n); i <= (m); ++i)
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define PI acos(-1)
#define eps 1e-9
#define rint register int
#define F(x) ((x)/3+((x)%3==1?0:tb))
#define G(x) ((x)<tb?(x)*3+1:((x)-tb)*3+2)
using namespace std;
typedef long long LL;
typedef pair<LL, int> pli;
typedef pair<int, int> pii;
typedef pair<double, int> pdi;
typedef pair<LL, LL> pll;
typedef pair<double, double> pdd;
typedef map<int, int> mii;
typedef map<char, int> mci;
typedef map<string, int> msi;
template<class T>
void read(T &res) {
  int f = 1; res = 0;
  char c = getchar();
  while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); }
  while(c >= '0' && c <= '9') { res = res * 10 + c - '0'; c = getchar(); }
  res *= f;
}
const int ne[8][2] = {1, 0, -1, 0, 0, 1, 0, -1, -1, -1, -1, 1, 1, -1, 1, 1};
const int INF = 0x3f3f3f3f;
const int N = 510;
const LL Mod = 1e9+7;
const int M = 1e6+10;
char tu[N][N];
int n, m, k, ans, cnt;
void dfs(int x, int y) {
  //cout << x << " " << y << " " << cnt << " " << ans-k << endl;
  for(int i = 0, tx, ty; i < 4; ++i) {
    tx = x + ne[i][0], ty = y + ne[i][1];
    if(tx >=1 && ty >= 1 && tx <= n && ty <= m && tu[tx][ty] == 'X') {
      if(cnt == ans-k) return;
      tu[tx][ty] = '.'; ++cnt;
      dfs(tx, ty);
    }
  }
}
int main() {
  scanf("%d %d %d", &n, &m, &k);
  int fx, fy;
  _rep(1, n, i) {
    scanf("%s", tu[i]+1);
    _rep(1, m, j) if(tu[i][j] == '.') {
      tu[i][j] = 'X', ++ans;
      fx = i; fy = j;
    }
  }
  tu[fx][fy] = '.'; ++cnt; dfs(fx, fy);
  _rep(1, n, i) printf("%s\n", tu[i]+1);
  return 0;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值