简体   繁体   English

Java-通过2D字符数组搜索单词?

[英]Java - Searching through a 2D array of characters for words?

So I've been creating a program that plays boggle when the user enters a word, it runs a search for the first letter through a 2D array of characters (the boggle board) and if it finds it, it searches all the characters around it. 因此,我一直在创建一个程序,当用户输入一个单词时,该程序将播放boggle,它会通过二维字符数组(boggle board)搜索第一个字母,如果找到它,它将搜索周围的所有字符。 But it only does this once and prints the letters around the first letter of the inputted word. 但是它只执行一次,并在输入单词的第一个字母周围打印字母。 How can I go about adding a function or adding onto my current functions that allows it to keep searching for letters through the inputted word until the full word is found, or is not found? 如何添加一个函数或添加到当前的函数中,以使其能够继续通过输入的单词搜索字母,直到找到或找不到完整的单词? Would I have to keep calling over the checkSurrounding() function? 我是否必须继续调用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]);
                }
            }
        }
    } 
}

Yes, I would do a recursion for checkSurrounding once you found a character that begins the start of the word. 是的,一旦您发现一个以单词开头的字符,我将对checkSurrounding进行递归。 In that function, I would include a parameter for the word itself. 在该函数中,我将包括单词本身的参数。 When checking for a character that comes next in the word, if I find a character that is at index 0 of word, then I recurse, but only looking at the last n-1 characters of word, ignoring the character you just found. 在检查单词中紧随其后的字符时,如果我找到了位于单词索引0处的字符,那么我会递归执行,但只会查看单词的后n-1个字符,而忽略刚才找到的字符。 If you were to use this implementation, you would need to keep track of which characters you've already come across, so that you ignore characters that have already been found. 如果要使用此实现,则需要跟踪已经遇到的字符,以便忽略已找到的字符。

You were actually very close to having everything you need to match the whole word. 实际上,您几乎已经拥有了匹配整个单词所需的一切。 The key is to use recursion to try to extend a partial match into the 8-neighbours of the currently matching character. 关键是使用递归尝试将部分匹配项扩展到当前匹配字符的8个邻居中。

One thing you have to be careful of is to not consider letters on the board more than once in a match. 您必须要注意的一件事是在比赛中不要多次考虑板上的字母。 The trick is to clear the current letter by setting it to blank before checking neighbors - this ensures that it can't be part of any future match. 诀窍是通过在检查邻居之前将其设置为空白来清除当前字母-这可以确保它不会成为任何将来匹配项的一部分。 Once you've considered all the neighbors you set the letter back to its original value. 一旦考虑了所有邻居,便将字母重新设置为其原始值。

The code below just counts how many different matches were found. 下面的代码仅统计发现了多少个不同的匹配项。 It would be really nice to keep track of the letter positions of each match, but that's a little trickier. 跟踪每场比赛的字母位置真的很不错,但这有点棘手。

This is mostly your code, with a few additions: 这主要是您的代码,还有一些附加内容:

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;
}

Test: 测试:

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);
}

Output: 输出:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM