CF377A Maze题解

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;
}

猜你喜欢

转载自blog.csdn.net/qq_43408978/article/details/108906691