poj 1204 Word Puzzles(字典树)

题目链接:http://poj.org/problem?id=1204

思路分析:由于题目数据较弱,使用暴力搜索;对于所有查找的单词建立一棵字典树,在图中的每个坐标,往8个方向搜索查找即可;

需要注意的是查找时不能匹配了一个单词就不在继续往该方向查找,因为在某个坐标的某个方向上可能会匹配多个单词,所以需要一直

查找直到查找到该方向上最后一个坐标;

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int KIND = 26;
const int MAX_N = 1000 + 10;
int row, column, num_word;
char map[MAX_N][MAX_N], words[MAX_N];
int dir[][2] = {-1, 0, -1, 1, 0, 1, 1, 1, 1, 0, 1, -1, 0, -1, -1, -1};
int pos[MAX_N][3];

struct Node {
    Node *next[KIND];
    bool end;
    int order;
    Node()
    {
        memset(next, 0, sizeof(next));
        end = false;
        order = 0;
    }
};

void CreateTrie(Node *root, char *str, int j)
{
    int i = 0;
    Node *p = root;

    while (str[i]) {
        int value = str[i] - 'A';
        if (p->next[value] == NULL)
            p->next[value] = new Node();
        p = p->next[value];
        ++i;
    }
    p->end = true;
    p->order = j;
}

void Search(Node *root, int i, int j, int k)
{
    Node *p = root;
    int pos_i = i, pos_j = j, value = 0;

    while (p && 0 <= pos_i && pos_i < row && 0 <= pos_j && pos_j < column) {
        value = map[pos_i][pos_j] - 'A';
        if (p->next[value]) {
            if (p->next[value]->end) {
                pos[p->next[value]->order][0] = i;
                pos[p->next[value]->order][1] = j;
                pos[p->next[value]->order][2] = k;
            }
            pos_i += dir[k][0];
            pos_j += dir[k][1];
            p = p->next[value];
        } else
            break;
    }
}

int main()
{
    while (scanf("%d %d %d
", &row, &column, &num_word) != EOF) {
        Node *root = new Node;

        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < column; ++j)
                scanf("%c", &map[i][j]);
            scanf("
");
        }
        for (int i = 0; i < num_word; ++i) {
            scanf("%s", words);
            CreateTrie(root, words, i);
        }
        for (int i = 0; i < row; ++i)
            for (int j = 0; j < column; ++j)
                for (int k = 0; k < 8; ++k)
                    Search(root, i, j, k);
        for (int i = 0; i < num_word; ++i)
            printf("%d %d %c
", pos[i][0], pos[i][1], pos[i][2] + 'A');
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tallisHe/p/4660144.html