发布于 

Maze

Maze

Codeforces Problem 377A

这题也算是一道比较好些的题目,但是前提是能想出正确的解法。

题目来源: Codeforces

分析

题目要求在给出的棋盘中加入\(k\)面墙,并且能够使得最后所有空白的块联通。如果我们从墙的角度出发,实际判断该从哪里放墙是十分复杂的。但是如果我们从空白的角度出发,我们会发现我们的目的只是确保空白块联通即可。所以我们可以先将所有的空白块设为X(墙),然后从其中某一点开始搜索,生成一个制定大小的联通块即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <queue>

using namespace std;

char a[510][510];

struct Node{
trueint x,y;
trueNode(int x,int y):x(x),y(y) {}
};

queue<Node> q;
const int xp[] = {0,0,-1,1};
const int yp[] = {1,-1,0,0};

void bfs(int x,int y,int cnt)
{
trueif (cnt==0)
truetruereturn;

trueq.push(Node(x,y));

truewhile (!q.empty())
true{
truetrueNode t = q.front();
truetrueq.pop();
truetrueif (a[t.x][t.y]=='.')
truetruetruecontinue;

truetruea[t.x][t.y] = '.';

truetrue//cout << "[ " << t.x << ", " << t.y << "] in " << cnt << endl;
truetruecnt --;
truetrueif (cnt==0)
truetruetruebreak;

truetruefor (int i = 0; i<4; i++)
truetruetrueif (a[t.x+xp[i]][t.y+yp[i]]=='X')
truetruetruetrueq.push(Node(t.x+xp[i],t.y+yp[i]));
true}
}

int main()
{
trueint n,m,k;
truecin >> n >> m >> k;

truefor (int i = 0; i<=n+1; i++)
truetruefor (int j = 0; j<=m+1; j++)
truetruetruea[i][j] = '#';

trueint cnt = n * m;
truefor (int i = 1; i<=n; i++)
truetruefor (int j = 1; j<=m; j++)
truetrue{
truetruetruecin >> a[i][j];
truetruetrueif (a[i][j]=='#')
truetruetruetruecnt --;
truetruetrueelse a[i][j] = 'X';
truetrue}

truebool flag = false;
truefor (int i = 1; i<=n; i++)
true{
truetruefor (int j = 1; j<=m; j++)
truetruetrueif (a[i][j]=='X')
truetruetrue{
truetruetruetruebfs(i,j,cnt-k);
truetruetruetrueflag = true;
truetruetruetruebreak;
truetruetrue}
truetrueif (flag)
truetruetruebreak;
true}

truefor (int i = 1; i<=n; i++)
true{
truetruefor (int j = 1; j<=m; j++)
truetruetruecout << a[i][j];
truetruecout << endl;
true}
}

本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

本站由 [@Songer](https://blog.songer.xyz/) 创建,使用 Stellar 作为主题。