Description
Input
Output
Sample Input
20 20 10 QWSPILAATIRAGRAMYKEI AGTRCLQAXLPOIJLFVBUQ TQTKAZXVMRWALEMAPKCW LIEACNKAZXKPOTPIZCEO FGKLSTCBTROPICALBLBC JEWHJEEWSMLPOEKORORA LUPQWRNJOAAGJKMUSJAE KRQEIOLOAOQPRTVILCBZ QOPUCAJSPPOUTMTSLPSF LPOUYTRFGMMLKIUISXSW WAHCPOIYTGAKLMNAHBVA EIAKHPLBGSMCLOGNGJML LDTIKENVCSWQAZUAOEAL HOPLPGEJKMNUTIIORMNC LOIUFTGSQACAXMOPBEIO QOASDHOPEPNBUYUYOBXB IONIAELOJHSWASMOUTRK HPOIYTJPLNAQWDRIBITG LPOINUYMRTEMPTMLMNBO PAFCOPLHAVAIANALBPFS MARGARITA ALEMA BARBECUE TROPICAL SUPREMA LOUISIANA CHEESEHAM EUROPA HAVAIANA CAMPONESA
Sample Output
0 15 G 2 11 C 7 18 A 4 8 C 16 13 B 4 15 E 10 3 D 5 1 E 19 7 C 11 11 H
解题思路:
输入需要查找的单词时时,为该单词建立字典树,在单词的结尾处记录该单词的编号,然后对整个图进行暴搜,以图中的每个点作为起点,从八个方向分别查找。
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> using namespace std; const int maxn = 26; char map[1005][1005], word[1005][1005]; int ans[1005][3]; // 记录三个答案,分别为坐标x,y,和方向 int l, c, w; bool visited[1005]; int dir[8][2] = {-1,0,-1,1,0,1,1,1,1,0,1,-1,0,-1,-1,-1}; //八个方向从北开始按顺势针排序 struct Trie { int n; Trie *next[maxn]; }; Trie *root; void init() { root = (Trie *)malloc(sizeof(Trie)); for(int i = 0; i < maxn; i++) { root -> next[i] = NULL; root -> n = -1; // 建立新指针的时候,n都赋为-1,这样所有n只能为-1或编号两种可能 } } void insert(char *word, int id) { Trie *temp = root; for(int i = 0; i < strlen(word); i++) { int pos = word[i] - 'A'; if(temp -> next[pos] == NULL) { Trie *cur = (Trie *)malloc(sizeof(Trie)); for(int j = 0; j < maxn; j++) { cur -> next[j] = NULL; cur -> n = -1; } temp -> next[pos] = cur; } temp = temp -> next[pos]; } temp -> n = id; // 单词结尾处记录单词编号 } void search(int x,int y,int d) { Trie *temp = root; int xx = x, yy = y; while(xx >= 0 && xx < l && yy >=0 && yy <c) { if(temp -> next[map[xx][yy] - 'A'] == NULL) //如果指针为空就跳出 break; else temp = temp -> next[map[xx][yy] - 'A']; // 否则指针下移 if(temp -> n != -1) // 一直找到单词的末尾处 { if(!visited[temp -> n]) // 已访问过就不需要记录答案 { visited[temp -> n] = 1; ans[temp -> n][0] = x; ans[temp -> n][1] = y; ans[temp -> n][2] = d; } } xx += dir[d][0]; // 朝某一方向搜索 yy += dir[d][1]; } } int main() { scanf("%d%d%d", &l, &c, &w); for(int i = 0; i < l; i++) scanf("%s", map[i]); init(); memset(visited, 0, sizeof(visited)); for(int i = 0; i < w; i++) { scanf("%s", word[i]); insert(word[i], i); // 建树 } for(int i = 0; i < l; i++) //对整个图进行暴搜 for(int j = 0; j < c; j++) for(int k = 0; k < 8; k++) search(i,j,k); for(int i = 0; i < w; i++) printf("%d %d %c\n", ans[i][0], ans[i][1], ans[i][2] + 'A'); }
Word Puzzles(字典树),布布扣,bubuko.com
原文:http://blog.csdn.net/userluoxuan/article/details/38439545