水题,我用的是DFS, 刚开始没注意题目要求只能在一个方向搜,WA了几次。。。。以后做题一定要好好审题。。。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef long long ll;
typedef unsigned long long unll;
using namespace std;
const int maxint = -1u>>1;
char b[MAXX][MAXX];
int m1[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int m2[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int m, n;
void dfs(const char *word, int x, int y, int pos, int size, bool &found,
int dx, int dy)
{
if(x > m || y > n || x < 1 || y < 1
|| b[x][y] != word[pos] || found)
return ;
if(pos >= size-1 && word[pos] == b[x][y]){
found = true;
return;
}
dfs(word, x+dx, y+dy, pos+1, size, found, dx, dy);
}
int main()
{
//freopen("test.in" ,"r", stdin);
int ncase;
scanf("%d" , &ncase);
while(ncase--)
{
memset(b, '.', sizeof(b));
scanf("%d %d", &m, &n);
getchar();
for(int i = 1; i <= m; i++){
char tmp[55];
gets(tmp);
for(int j = 0; j < n; j++){
b[i][j+1] = tolower(tmp[j]);
}
}
int k;
scanf("%d", &k);
getchar();
for(int zz = 0; zz < k; zz++){
string s;
getline(cin, s);
for(int jj = 0; jj < s.size(); jj++) s[jj] = tolower(s[jj]);
int found = 0;
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++)
{
if(b[i][j] == tmp[0]){
bool ok = false;
for(int dire = 0; dire < 8; dire++){
dfs(s.c_str(), i, j, 0, s.size(), ok, m1[dire], m2[dire]);
if(ok) break;
}
if(ok)
{
printf("%d %d\n", i, j);
found = 1;
break;
}
}
}
if(found) break;
}
}
if(ncase) printf("\n");
}
return 0;
}