1. 程式人生 > 其它 >CF525D Arthur and Walls (搜尋)

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("\n"); 62 } 63 return 0; 64 }