Ejemplo n.º 1
0
  public void search(
      boolean[][] used,
      char[][] board,
      StringBuilder word,
      int i,
      int j,
      Trie trie,
      Set<String> wordsList) {
    if (trie.search(word.toString())) {
      wordsList.add(word.toString());
      return;
    }

    if (trie.startsWith(word.toString())) {
      if (i > 0 && !used[i - 1][j]) {
        used[i - 1][j] = true;
        word.append(board[i - 1][j]);
        search(used, board, word, i - 1, j, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }

      if (i < board.length - 1 && !used[i + 1][j]) {
        used[i + 1][j] = true;
        word.append(board[i + 1][j]);
        search(used, board, word, i + 1, j, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }

      if (j > 0 && !used[i][j - 1]) {
        used[i][j - 1] = true;
        word.append(board[i][j - 1]);
        search(used, board, word, i, j - 1, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }

      if (j < board[0].length - 1 && !used[i][j + 1]) {
        used[i][j + 1] = true;
        word.append(board[i][j + 1]);
        search(used, board, word, i, j + 1, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }
    }
  }
Ejemplo n.º 2
0
    public void dfs(char[][] board, boolean[][] visited, String str, int i, int j, Trie trie) {
      int m = board.length;
      int n = board[0].length;

      if (i >= m || j >= n || i < 0 || j < 0) return;

      if (visited[i][j]) return;

      str = str + board[i][j];
      //   System.out.println(str);

      if (!trie.startsWith(str)) return;

      if (trie.search(str)) {
        result.add(str);
      }

      visited[i][j] = true;
      dfs(board, visited, str, i - 1, j, trie);
      dfs(board, visited, str, i + 1, j, trie);
      dfs(board, visited, str, i, j - 1, trie);
      dfs(board, visited, str, i, j + 1, trie);
      visited[i][j] = false;
    }