Q10010: Where's Waldorf? 字符搜索

Q10010: Where's Waldorf?

給你一個m*n的字元方塊(1 <= m,n <=50),以及一些字串,請你找出這些字串在字元方塊中出現的位置。請參考Sample Output。

我們在字元方塊中尋找字串的方向可以有8個:往左、往右、往上、往下、往左上、往左下、往右上、往右下。另外,請忽略字元大小寫,即 Aa 應被視為相同的字元。

Input

輸入的第一列有一個整數代表以下有幾組測試資料。

每組測試資料的第1列,有2個整數m,n(1 <= m,n <=50),代表接下來的文字方塊有m列,每列有n個字元。在文字方塊之後的一列有一個整數 k,代表接下來的k列為欲搜尋的字串。請參考Sample Input。

Output

每組測試資料中欲搜尋字串,請輸出其出現在文字方塊中的位置X Y。(第X列,第Y行)

如果在文字方塊中該字串出現在不只一個地方,請輸出在最左上方的那一組(以欲搜尋字串的第一個字元來比較)。所有欲搜尋的字串至少出現一次。

測試資料間也請空一列。

Sample input

2

8 11
abcDEFGhigg
hEbkWalDork
FtyAwaldORm
FtsimrLqsrc
byoArBeDeyv
Klcbqwikomk
strEBGadhrb
yUiqlxcnBjf
4
Waldorf
Bambi
Betty
Dagbert

2 2
ab
Ca
3
a
ba
a 

Sample Output

2 5
2 3
1 2
7 8

1 1
1 2
1 1
在网上找到的一份代码,写得挺不错的,看了代码之后学习了
#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;
}
原文地址:https://www.cnblogs.com/UnGeek/p/2551526.html