AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 1. Elementary Problem Solving :: String
Description
在一个由字母组成的网格中,寻找单词。
单词无论大小写,但必须是在一条直线上,可以是水平、竖直或者是斜对角线的。
如果单词多次出现,仅输出最上面方,然后最靠最左的单词的首字母位置。
Type
String
Analysis
枚举每个单词的首字母位置,向八个方向检查单词是否出现即可。
Solution
// UVaOJ 10010
// Where's Waldorf?
// by A Code Rabbit
#include
#include
#include
const int MAXN = 52;
struct Point {
int x, y;
};
const Point WAY[] = {
{-1, -1}, {-1, 0}, {-1, 1},
{ 0, -1}, { 0, 1},
{ 1, -1}, { 1, 0}, { 1, 1},
};
int n, m, k;
int grid[MAXN][MAXN];
char word[MAXN];
bool Find(int x, int y);
int main() {
int tot_case;
scanf("%d", &tot_case);
while (tot_case--) {
scanf("%d%d", &n, &m);
getchar();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
grid[i][j] = tolower(getchar());
getchar();
}
scanf("%d", &k);
getchar();
for (int i = 0; i < k; i++) {
gets(word);
for (int j = 0; j < strlen(word); j++)
word[j] = tolower(word[j]);
bool bo = false;
for (int x = 1; x <= n; x++)
for (int y = 1; y <= m; y++) {
if (!bo && Find(x, y)) {
printf("%d %d\n", x, y);
bo = true;
}
}
}
printf("%s", tot_case ? "\n" : "");
}
return 0;
}
bool Find(int x, int y) {
for (int i = 0; i < 8; i++) {
bool bo = true;
for (int j = 0; j < strlen(word); j++) {
if (grid[x + WAY[i].x * j][y + WAY[i].y * j] != word[j]) {
bo = false;
break;
}
}
if (bo)
return true;
}
return false;
}