IT民工
加油!

这道题是要找到字符串在字符矩阵里的位置,并输出其头字母的坐标。我们先找到首字母的位置,

然后按照八个方向当中的一个搜索,如果能找到完整的字符串,就输出坐标。与DFS每个点按照

八个方向搜索不同的是,这里只是按照一个方向一个方向地搜索。所以搜索函数也稍有不同。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctype.h>
#define MAXN 60

int cas, m, n, q;
int x, y;
char r[MAXN][MAXN];
const int dx[] = { 1, 1, 1, -1, -1, -1, 0, 0};
const int dy[] = { 0, 1, -1, 0, 1, -1, 1, -1};

void search( const char *a, int &x, int &y)
{
int pos, nx, ny;
for( int i = 1; i <= m; i ++)
{
for( int j = 1; j <= n; j ++)
{
if( r[i][j] == a[0])
{
for( int k = 0; k < 8; k ++)
{
pos = 0; nx = i; ny = j;
while( a[pos] && a[pos] == r[nx][ny])
{
nx += dx[k];
ny += dy[k];
pos ++;
}
if( a[pos] == 0)
{
x = i;
y = j;
return;
}
}
}
}
}
}

int main()
{
scanf( "%d", &cas);
for( int tt = 1; tt <= cas; tt ++)
{
char word[MAXN];
if( tt >= 2) printf( "\n");
memset( r, 0, sizeof r);
scanf( "%d%d", &m, &n);
for( int i = 1; i <= m; i ++)
{
scanf( "%s", word);
for( int j = 1; j <= n; j ++)
{
r[i][j] = tolower(word[j - 1]);
}
}

scanf( "%d", &q);
while( q --)
{
scanf( "%s", word);
int len = strlen( word);
for( int i = 0; i < len; i ++)
{
word[i] = tolower( word[i]);
}
search( word, x, y);
printf( "%d %d\n", x, y);
}
}
return 0;
}

 

posted on 2012-01-28 17:13  找回失去的  阅读(506)  评论(0编辑  收藏  举报