[codeforces525D]BFS

题目大意:

给定一个包含'.'和'*'的地图,每次操作可以把'*'->'.',用最少的操作使得新图满足条件:所有的连通块为矩形('.'为可达点)

解法:

用bfs来模拟操作的过程,对于一个2*2的块,如果只有一个‘*’,那么这个'*'是肯定要被变为'.',于是又可能影响这个点周围相邻的点,一开始把所有满足这个形式的点加入队列,考虑所有周围的点,如果有新的点满足这个形式,则加入队列。代码如下

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <map>
 6 #include <queue>
 7 #include <cmath>
 8 #include <vector>
 9 #include <ctime>
10 #include <cctype>
11 
12 using namespace std;
13 
14 #define mem0(a) memset(a, 0, sizeof(a))
15 #define lson l, m, rt << 1
16 #define rson m + 1, r, rt << 1 | 1
17 #define define_m int m = (l + r) >> 1
18 #define Rep(a, b) for(int a = 0; a < b; a++)
19 #define lowbit(x) ((x) & (-(x)))
20 #define constructInt4(name, a, b, c, d) name(int a = 0, int b = 0, int c = 0, int d = 0): a(a), b(b), c(c), d(d) {}
21 #define constructInt3(name, a, b, c) name(int a = 0, int b = 0, int c = 0): a(a), b(b), c(c) {}
22 #define constructInt2(name, a, b) name(int a = 0, int b = 0): a(a), b(b) {}
23 
24 typedef double db;
25 typedef long long LL;
26 typedef pair<int, int> pii;
27 
28 const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};
29 const int dy[8] = {0, -1, 0, 1, -1, 1, 1, -1};
30 const int maxn = 1e6 + 7;
31 const int maxm = 1e5 + 7;
32 const int MD = 1e9 +7;
33 const int INF = 1e9 + 7;
34 
35 queue<pii> Q;
36 
37 char s[2015][2015];
38 
39 int n, m;
40 
41 bool ok(int x, int y) {
42     return x >= 0 && x < n && y >= 0 && y < m && s[x][y] == '.';
43 }
44 
45 bool chk(int x, int y) {
46     if (s[x][y] == '.') return false;
47     int d[] = {-1, 0, -1, 1, 0, 1, 1, 1, 1, 0, 1, -1, 0, -1, -1, -1, -1, 0};
48     bool t[10];
49     for (int i = 0; i < 18; i += 2) {
50         if (ok(x + d[i], y + d[i + 1])) {
51             t[i >> 1] = true;
52         }
53         else {
54             t[i >> 1] = false;
55         }
56     }
57     for (int i = 0; i < 8; i += 2) {
58         if (t[i] && t[i + 1] && t[i + 2]) {
59             return true;
60         }
61     }
62     return false;
63 }
64 
65 int main() {
66     //freopen("in.txt", "r", stdin);
67     cin >> n >> m;
68     for (int i = 0; i < n; i++) {
69         scanf("%s", s[i]);
70     }
71     for (int i = 0; i < n; i++) {
72         for (int j = 0; j < m; j++) {
73             if (chk(i, j)) {
74                 Q.push(make_pair(i, j));
75                 s[i][j] = '.';
76             }
77         }
78     }
79     while (!Q.empty()) {
80         pii H = Q.front(); Q.pop();
81         for (int i = 0; i < 8; i++) {
82             int xx = H.first + dx[i], yy = H.second + dy[i];
83             if (chk(xx, yy)) {
84                 Q.push(make_pair(xx, yy));
85                 s[xx][yy] = '.';
86             }
87         }
88     }
89     for (int i = 0; i < n; i++) {
90         puts(s[i]);
91     }
92     return 0;
93 }
View Code
原文地址:https://www.cnblogs.com/jklongint/p/4373074.html