あなたのおばあさんのために、初めて 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)