【发布时间】:2013-06-20 04:09:38
【问题描述】:
给定一个二维字符矩阵,我们必须检查给定的单词是否存在于其中。 例如
s f t
d a h
r y o
我们可以在里面找到“老鼠” (自上而下、笔直、对角线或任意路径).. 即使是倒序。用最少的复杂性。
我的方法是
While traversing the 2d matrix ( a[][] ) row wise.
If ( a[i][j] == first character of given word ) {
search for rest of the letters in 4 directions i.e. right, right diagonally down, down and left diagonally down.
} else if( a[i][j] == last character of the given word ) {
search for remaining characters in reverse order in 4 directions i.e. left, right diagonally up, up, left diagonally up.
}
有没有更好的方法?
【问题讨论】:
-
什么是最好的方法,部分取决于单词的规则,你没有足够清楚地说明问题是可以解决的。一个单词的字母是否必须在一条直线上,或者任何路径都可以?路径可以自己交叉和/或重复使用字母吗?此外,应用了两种不同的 O() 函数:一种用于预处理,一种用于搜索。预处理后,你可能会先寻找稀有字母或稀有元组
-
这里的一个重要问题是:要搜索的单词的最大长度是多少?这可以改变整个故事。
标签: c++ algorithm multidimensional-array