现在是我为你祖母编写她的第一个 Java 单词搜索程序的时候了。但不是让她通过在字母网格中查找单词来完成所有工作,而是使用递归函数4WaySearch
为她做这件事!
唯一的问题是:
我发现很难概念化一个递归算法,该算法在网格中一次开始时构建每个可能的字母组合。
这是我已经编写的代码,我认为这是朝着正确方向迈出的一大步:
/*
* This is the method that calls itself repeatedly to wander it's way
* through the grid using a 4 way pattern,
* creating every possibly letter combination and checking it against a
* dictionary. If the word is found in the dictionary, it gets added to a
* collection of found words.
*
* Here an example of a 3x3 grid with the valid words of RATZ and BRATZ, but
* the word CATZ isn't valid. (the C is not tangent to the A).
*
* CXY
* RAT
* BCZ
*
* @param row Current row position of cursor
* @param col Current column position of cursor
*/
private void 4WaySearch(int row, int col) {
// is cursor outside grid boundaries?
if (row < 0 || row > ROWS - 1 || col < 0 || col > COLS - 1)
return;
GridEntry<Character> entry = getGridEntry(row, col);
// has it been visited?
if (entry.hasBreadCrumb())
return;
// build current word
currentWord += entry.getElement(); // returns character
// if dictionay has the word add to found words list
if (dictionary.contains(currentWord))
foundWords.add(currentWord);
// add a mark to know we visited
entry.toggleCrumb();
// THIS CANT BE RIGHT
4WaySearch(row, col + 1); // check right
4WaySearch(row + 1, col); // check bottom
4WaySearch(row, col - 1); // check left
4WaySearch(row - 1, col); // check top
// unmark visited
entry.toggleCrumb();
// strip last character
if (currentWord.length() != 0)
currentWord = currentWord.substring(
0,
(currentWord.length() > 1) ?
currentWord.length() - 1 :
currentWord.length()
);
}
在我的脑海中,我将搜索算法可视化为递归树遍历算法,但每个节点(本例中的条目)有 4 个子节点(切线条目),叶节点是网格的边界。
此外,初始进入函数时光标的位置由此处伪编码的简单 for 循环确定:
for (int r = 0; r < ROWS; r++)
for (int c = 0; r < COLS; c++)
4WaySearch(r,c);
end for;
end for;
我一直在考虑这个问题,并尝试了不同的方法......但我似乎仍然无法将我的思想包裹在它周围并让它发挥作用。有人可以给我看灯吗?(为了我和你的祖母!:D)