1. 程式人生 > >Luogu P1101 單詞方陣

Luogu P1101 單詞方陣

can false 一個 pre strong 分離 蘊含 判斷 put

明明是一道水題,我還找不出 bug 來。。。原本在 DFS 途中記錄單詞串,只好使用笨方法,在結尾加一個 for 記錄單詞串。終於過了。

思路:枚舉圖中每一個點進行 DFS,途中判斷訪問的點是否為連續元素(“yizhong”字符串中連續),如果不是返回;進行下一層 DFS,如果返回值 True 則直接層層返回 True,強行退出。

 1 /* P1101 單詞方陣
 2  * Au: GG
 3  */
 4 #include <cstdio>
 5 #include <cstdlib>
 6 #include <cstring>
 7 #include <cmath>
 8
#include <ctime> 9 #include <iostream> 10 #include <algorithm> 11 using namespace std; 12 const int N = 103; 13 int n, dir[8][2] = { 14 {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, 15 {0, 1}, {1, -1}, {1, 0}, {1, 1} 16 }; 17 char g[N][N], str[] = "\0yizhong"; // 強行空出 str[0] 18 bool v[N][N];
19 20 inline char read() { 21 char c = getchar(); 22 while(!isalpha(c)) c = getchar(); 23 return c; 24 } 25 26 bool dfs(int x, int y, int d, int cnt) { 27 if (g[x][y] != str[cnt]) return false; 28 if (cnt == 7) { 29 while (cnt--) { 30 v[x][y] = true; 31 x -= dir[d][0
]; y -= dir[d][1]; 32 } 33 return true; 34 } 35 int xx = x + dir[d][0], yy = y + dir[d][1]; 36 if (1 <= xx && xx <= n && 1 <= yy && yy <= n) 37 if (dfs(xx, yy, d, cnt + 1)) return true; 38 } 39 40 int main() { 41 // freopen("p1101.in", "r", stdin); 42 scanf("%d", &n); 43 for (int i = 1; i <= n; i++) 44 for (int j = 1; j <= n; j++) 45 g[i][j] = read(); 46 for (int i = 1; i <= n; i++) 47 for (int j = 1; j <= n; j++) 48 for (int k = 0; k < 8; k++) 49 dfs(i, j, k, 1); 50 for (int i = 1; i <= n; i++) { 51 for (int j = 1; j <= n; j++) { 52 if (v[i][j]) putchar(g[i][j]); 53 else putchar(*); 54 } 55 putchar(\n); 56 } 57 return 0; 58 }

題面中的樣例數據(與樣例數據答案分離):

8
qyizhong
gydthkjy
nwidghji
orbzsfgz
hhgrhwth
zzzzzozo
iwdfrgng
yyyygggg

題面:


Luogu P1101 單詞方陣

題目描述

給一nXn的字母方陣,內可能蘊含多個“yizhong”單詞。單詞在方陣中是沿著同一方向連續擺放的。擺放可沿著8個方向的任一方向,同一單詞擺放時不再改變方向,單詞與單詞之間[color=red]可以[/color]交叉,因此有可能共用字母。輸出時,將不是單詞的字母用“*”代替,以突出顯示單詞。例如:

輸入:
    8                     輸出:
    qyizhong              *yizhong
    gydthkjy              gy******
    nwidghji              n*i*****
    orbzsfgz              o**z****
    hhgrhwth              h***h***
    zzzzzozo              z****o**
    iwdfrgng              i*****n*
    yyyygggg              y******g

輸入輸出格式

輸入格式:

第一行輸入一個數n。(7<=n<=100)。

第二行開始輸入nXn的字母矩陣。

輸出格式:

突出顯示單詞的nXn矩陣。

輸入輸出樣例

輸入樣例#1:
7
aaaaaaa
aaaaaaa
aaaaaaa
aaaaaaa
aaaaaaa
aaaaaaa
aaaaaaa
輸出樣例#1:
*******
*******
*******
*******
*******
*******
*******

Luogu P1101 單詞方陣