本文包含以下内容:
一.思路
二.代码
三.总结
一.思路
字符串搜索问题。因为原题中说了
“A word matches a straight, uninterrupted line of letters in the grid.”
(一个单词匹配网格中的一条直的、不间断的线)
因为有这句话,使搜索策略变得非常简单:
从上至下,从左至右历遍grid,如果发现一个字符与word里开头的字符匹配,分上下左右、 右上右下、左上左下八个方向搜索。
如果发现一个方向上完全匹配,停止循环,输出位置。
注意:如果没有“A word matches a straight, uninterrupted line of letters in the grid.”这句话,可能会涉及到深度优先之类递归搜索。
二.代码
#include<iostream>
using namespace std;
int m, n, k;
char g[50][50];
char w[50];
char c;
//此处有重大错误,记得写总结
void invert_to_lower(char a[]) {
int n = strlen(a);
for (int i = 0; i < n; i++)
if (a[i] >= 'A'&&a[i] <= 'Z')/
a[i] += 32;
}
int main() {
FILE* stream;
freopen_s(&stream, "C:\\Users\\zgwng\\Desktop\\10010.txt", "r", stdin);
//input
cin >> m >> n;
c = getchar();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
g[i][j] = getchar();
c = getchar();
}
cin >> k;
while (k--) {
cin >> w;
//invert
invert_to_lower(w);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (g[i][j] >= 'A'&& g[i][j] <= 'Z')
g[i][j] += 32;
//search
int i, j;
int found = 0;
int len = strlen(w);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (g[i][j] != w[0])continue;
//up
if ((i + 1) >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i - p][j]) {
f = 0; break;
}
if (f) { found = 1; break; }
}
//down
if (m - i >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i + p][j]) { f = 0; break; }
if (f) { found = 1; break; }
}
//left
if (j + 1 >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i][j - p]) { f = 0; break; }
if (f) { found = 1; break; }
}
//right
if (n - j >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i][j + p]) { f = 0; break; }
if (f) { found = 1; break; }
}
//right up
if (n - j >= len&&i + 1 >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i - p][j + p]) { f = 0; break; }
if (f) { found = 1; break; }
}
//right down
if (n - j >= len&&m - i >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i + p][j + p]) { f = 0; break; }
if (f) { found = 1; break; }
}
//left up
if (j + 1 >= len&&i + 1 >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i - p][j - p]) { f = 0; break; }
if (f) { found = 1; break; }
}
//left down
if (j + 1 >= len&&m - i >= len) {
int f = 1;
for (int p = 1; p < len; p++)
if (w[p] != g[i + p][j - p]) { f = 0; break; }
if (f) { found = 1; break; }
}
}//end j
if (found)break;
}//end i
cout << i+1 << " " << j+1<<endl;
}
return 0;
}
三.总结
1.cin不会舍弃\n,要用一个getchar读取
2.大小写字母转化问题:大写到小写+32,或者-‘A’+'a'
3.注意break和continue
if (g[i][j] != w[0])continue;