Beispiel #1
0
  private void dfs(char[][] board, int x, int y, Trie root, List<String> result) {
    char c = board[x][y];
    if (c == '#' || root.children[c - 'a'] == null) {
      return;
    }

    root = root.children[c - 'a'];
    if (root.word != null) {
      result.add(root.word);
      root.word = null;
    }

    board[x][y] = '#';
    if (x > 0) {
      dfs(board, x - 1, y, root, result);
    }

    if (x < board.length - 1) {
      dfs(board, x + 1, y, root, result);
    }

    if (y > 0) {
      dfs(board, x, y - 1, root, result);
    }

    if (y < board[0].length - 1) {
      dfs(board, x, y + 1, root, result);
    }

    board[x][y] = c;
  }
Beispiel #2
0
  private void addToTrie(Trie root, String word) {
    for (char c : word.toCharArray()) {
      int index = c - 'a';
      if (root.children[index] == null) {
        root.children[index] = new Trie();
      }
      root = root.children[index];
    }

    root.word = word;
  }