打印所有可能的话,从角色的二维数组 [英] Printing all possible words from a 2D array of characters

查看:98
本文介绍了打印所有可能的话,从角色的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近偶然在本次采访的问题,

Stumbled upon this interview question recently,

给定一个2维字符数组和字典,其中一个字可以被搜索 O(1)的时间。需要打印的数组,它是present在字典中的所有单词。可形成在任何方向的Word但最终在阵列的任何一边。(不必担心太多关于字典)

Given a 2-dimensional array of characters and a dictionary in which a word can be searched in O(1) time. Need to print all the words from array which are present in dictionary. Word can be formed in any direction but has to end at any edge of array.(Need not worry much about the dictionary)

输入:

a f h u n
e t a i r
a e g g o
t r m l p

输出:

after
hate
hair
air
eat
tea

请注意:这里的蛋是不是字典中的单词,因为它不是结束,在阵列边缘

Note: Here "egg" is not a dictionary word because its not ending at the edge of array.

我已经看到了类似的问题过,但始终没能想出一个好的算法来解决这类问题的。关于如何处理这类问题(形成了从字符数组的话)任何帮助将是非常有益的。

I've seen similar questions before, but was never able to think of a good algorithm to solve these kind of problems. Any help on how to approach these kind of problems (forming words from arrays of characters) will be highly helpful.

(我能想到的唯一的办法是找到二维阵列中的所有可能的字符排列,并检查它是否在阵列的边缘处结束,并检查置换是从澳词典中的有效字(1)时间)

(The only way I could think of is to find all possible permutations of characters in the 2D array, and check if it ends on the edge of the array, and check if the permutation is a valid word from the dictionary in O(1) time)

推荐答案

打开阵列成图,使每个细胞 [I,J] 具有一边缘与第4邻居每一个共享 [I + 1,J],[I-1,j]时,[I,J + 1],[I,J-1] 。 然后,在每个阵列边缘的细胞运行DFS和,并保持检查字典是否 相反的词是在里面。

Turn the array into a graph so that each cell [i,j] has an edge shared with each one of its 4 neighbors [i+1,j], [i-1,j], [i,j+1], [i,j-1]. Then run DFS at each array-edge-cell and and keep checking the dictionary whether the word in reverse is in it.

这篇关于打印所有可能的话,从角色的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆