CF525D Arthur and Walls (搜索)

【题目】

https://www.luogu.com.cn/problem/CF525D

【分析】

当且仅当存在一个2*2矩阵出现以下四种情况时,有“*”需要被更改。

. .     . *   * .      . .
. *     . .   . .      * .
(可以看作是以“*”为中心,每逆时针旋转90°记录一次而形成的)

所以可以枚举每个“*”的位置,判断当前“*”是否出现上述情况。如果出现,则将“*”变为“.”。否则继续判断下一个“*”。

【代码实现】

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n,m;
 4 char a[2020][2020];
 5 int mx[8] = {0, 1, -1, 0, 1, -1, -1, 1};
 6 int my[8] = {1, 0, 0, -1, 1, -1, 1, -1};
 7 
 8 bool judg(int x, int y){
 9     if(x < 1 || x > n) return 0;
10     if(y < 1 || y > m) return 0;
11     return (a[x][y] == '.');
12 }
13 
14 bool check(int i, int j){
15     if(judg(i - 1, j) && judg(i, j - 1) && judg(i - 1, j - 1)) return true;
16     if(judg(i - 1, j) && judg(i, j + 1) && judg(i - 1, j + 1)) return true;
17     if(judg(i + 1, j) && judg(i, j - 1) && judg(i + 1, j - 1)) return true;
18     if(judg(i + 1, j) && judg(i, j + 1) && judg(i + 1, j + 1)) return true;
19     return false;
20 }
21 
22 void dfs(int x, int y){
23     for(int i = 0; i < 8; ++ i){
24         int nx = x + mx[i];
25         int ny = y + my[i];
26         if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && a[nx][ny] == '*' && check(nx, ny))
27             a[nx][ny] = '.', dfs(nx, ny);
28     }
29 }
30 
31 int main(){
32     scanf("%d %d",&n,&m);
33     for(int i = 1; i <= n; ++ i)
34     {
35          for(int j = 1; j <= m; ++ j) 
36          {
37             cin>>a[i][j];//这块用不了scanf,不知道为啥。
38          }
39     }
40        
41     
42     for(int i = 1; i <= n; ++ i)
43     {
44         for(int j = 1; j <= m; ++ j)
45             if(a[i][j] == '*'){
46                 if(check(i, j)) 
47                 {
48                     a[i][j] = '.';
49                     dfs(i, j);
50                 }
51             }   
52         }
53          
54     
55     for(int i = 1; i <= n; ++ i)
56     {
57         for(int j = 1; j <= m; ++ j)
58         {
59             printf("%c",a[i][j]) ;
60         }
61         printf("
");
62     }
63     return 0;
64 }
原文地址:https://www.cnblogs.com/TheZealous/p/15541486.html