Uva-10010 (字符串处理,搜索)

2014-05-29 18:10:55

题意 & 思路:给出字母表,再给出单词,保证单词能够在字母表中匹配,方向可以是上下左右再加上45度方向,一共8个方向,输出最靠左上的单词第一个字符匹配位置。(被英语坑死了TAT,一开始DFS各种WA,后来发现根本不用在每个位置重判方向,哎,改了改DFS,牛刀杀鸡,水过)

#include 
#include 
#include 
using namespace std;
int len,k,t,m,n;
const int maxn = 50;

int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
char g[maxn + 5][maxn + 5],temp[maxn + 5],word[maxn + 5];
    
int DFS(int l,int c,int num,int d){
    if(num == len){
        return 1;
    }
    int tl = l + dir[d][0];
    int tc = c + dir[d][1];
    if(tl >= 1 && tl <= m && tc >= 1 && tc <= n && g[tl][tc] == word[num + 1]){
            if(DFS(tl,tc,num + 1,d)){
                return 1;
            }
    }
    return 0;
}

int main(){
    int i,j;
    scanf("%d",&t);
    while(t--){
        memset(g,0,sizeof(g));
        memset(temp,0,sizeof(temp));
        memset(word,0,sizeof(word));
        scanf("%d %d",&m,&n);
        for(i = 1; i <= m; i++){
            scanf("%s",temp + 1);
            for(j = 1; j <= n; j++){
                if(temp[j] >= 'A' && temp[j] <= 'Z'){
                    temp[j] += ('a' - 'A');
                }
                g[i][j] = temp[j];
            }
        }
        scanf("%d",&k);
        while(k--){
            scanf("%s",word + 1);
            len = strlen(word + 1);
            for(i = 1; i <= len; i++){
                if(word[i] >= 'A' && word[i] <= 'Z'){
                    word[i] += ('a' - 'A');
                }
            }
            int ok = 0;
            for(i = 1; i <= m; i++){
                for(j = 1; j <= n; j++){
                    if(g[i][j] == word[1]){
                        for(int p = 0; p < 8; p++){
                            if(DFS(i,j,1,p)){
                                ok = 1;
                                break;
                            }
                        }
                    }
                    if(ok) break;
                }
                if(ok) break;
            }
            printf("%d %d\n",i,j);
        }
        if(t){
            puts("");
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/naturepengchen/articles/3758861.html

你可能感兴趣的:(Uva-10010 (字符串处理,搜索))