[英]Java - Searching through a 2D array of characters for words?
因此,我一直在創建一個程序,當用戶輸入一個單詞時,該程序將播放boggle,它會通過二維字符數組(boggle board)搜索第一個字母,如果找到它,它將搜索周圍的所有字符。 但是它只執行一次,並在輸入單詞的第一個字母周圍打印字母。 如何添加一個函數或添加到當前的函數中,以使其能夠繼續通過輸入的單詞搜索字母,直到找到或找不到完整的單詞? 我是否必須繼續調用checkSurrounding()函數?
private static void checkForFirstLetter(char[][] boggle, String word) {
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
if(boggle[i][j] == word.charAt(0)) {
System.out.println("\nFound " + boggle[i][j] + " at (" + (j+1) + ", " + (i+1) + ")!");
checkSurrounding(boggle, j, i);
}
}
}
}
private static void checkSurrounding(char[][] boggle, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
if ((x + dx >= 0) && (x + dx < boggle.length)) {
for(int dy = -1; dy <= 1; dy++) {
if ((y + dy >= 0) && (y + dy < boggle[x + dx].length) && (!(dx == 0 && dy == 0))) {
System.out.print(boggle[y + dy][x + dx]);
}
}
}
}
}
是的,一旦您發現一個以單詞開頭的字符,我將對checkSurrounding進行遞歸。 在該函數中,我將包括單詞本身的參數。 在檢查單詞中緊隨其后的字符時,如果我找到了位於單詞索引0處的字符,那么我會遞歸執行,但只會查看單詞的后n-1個字符,而忽略剛才找到的字符。 如果要使用此實現,則需要跟蹤已經遇到的字符,以便忽略已找到的字符。
實際上,您幾乎已經擁有了匹配整個單詞所需的一切。 關鍵是使用遞歸嘗試將部分匹配項擴展到當前匹配字符的8個鄰居中。
您必須要注意的一件事是在比賽中不要多次考慮板上的字母。 訣竅是通過在檢查鄰居之前將其設置為空白來清除當前字母-這可以確保它不會成為任何將來匹配項的一部分。 一旦考慮了所有鄰居,便將字母重新設置為其原始值。
下面的代碼僅統計發現了多少個不同的匹配項。 跟蹤每場比賽的字母位置真的很不錯,但這有點棘手。
這主要是您的代碼,還有一些附加內容:
static int checkForFirstLetter(char[][] board, String word)
{
int count = 0;
for (int x = 0; x < board.length; x++) {
for (int y = 0; y < board.length; y++) {
if (board[x][y] == word.charAt(0)) {
count += checkSurrounding(board, x, y, word, 0);
}
}
}
return count;
}
static int checkSurrounding(char[][] board, int x, int y, String word, int i)
{
if (i == word.length())
return 1;
if (board[x][y] != word.charAt(i))
return 0;
int count = 0;
// Clear the current position so we don't consider it again in a match
board[x][y] = 0;
for (int dx = -1; dx <= 1; dx++) {
if ((x + dx >= 0) && (x + dx < board.length)) {
for (int dy = -1; dy <= 1; dy++) {
if ((y + dy >= 0) && (y + dy < board[x + dx].length) && (!(dx == 0 && dy == 0))) {
count += checkSurrounding(board, x + dx, y + dy, word, i + 1);
}
}
}
}
// Reinstate the character at the current position, which has to be at pos i in word
board[x][y] = word.charAt(i);
return count;
}
測試:
public static void main(String[] args)
{
char[][] board = {
{'o', 'x', 'o', 'x', 'o'},
{'x', 'o', 'x', 'o', 'x'},
{'o', 'x', 'o', 'x', 'o'},
{'x', 'o', 'x', 'o', 'x'},
{'o', 'x', 'o', 'x', 'o'}};
for(char[] b : board)
System.out.println(new String(b).replaceAll(".", "$0 "));
int count = checkForFirstLetter(board, "oxo");
System.out.printf("\nFound %d word(s)\n", count);
}
輸出:
o x o x o
x o x o x
o x o x o
x o x o x
o x o x o
Found 604 word(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.