import java.util.ArrayList;
import java.util.List;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
* This algorithm is to implement R-way tries set to store a dictionary and to check prefix
* Deep First Search to make up strings.
* @author Daihu
* @date 2017年2月22日
*/
public class {
private int row, col;
private TrieSET dic;
public (String[] dictionary) {
dic = new TrieSET();
for (String word: dictionary) {
dic.add(word);
}
}
* @param board
* @return the set of all valid words in the given board
*/
public Iterable<String> getAllValidWords(BoggleBoard board) {
List<String> container = new ArrayList<>();
boolean[][] marked;
row = board.rows();
col = board.cols();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String str = "";
marked = new boolean[row][col];
dfs(i, j, board, str, marked, container);
}
}
return container;
}
* DFS: recursively add char into string to check if in dictionary
* true for storing in container
*
* @param i, j: the position of the the begin char
* @param board
* @param str: store in container if this string is in dictionary
* @param marked: mark for checking if visited
* @param container: the result containing strings in dictionary
*/
private void dfs(int i, int j, BoggleBoard board, String str, boolean[][] marked, List<String> container) {
char letter;
if (i >= 0 && i < row && j >= 0 && j < col && !marked[i][j]) {
letter = board.getLetter(i, j);
if (letter == 'Q')
str += "QU";
else
str += letter;
if (str.length() > 2 && dic.contains(str) && !container.contains(str))
container.add(str);
if (!dic.isPrefix(str)) return;
marked[i][j] = true;
dfs(i+1, j, board, str, marked, container);
dfs(i-1, j, board, str, marked, container);
dfs(i, j+1, board, str, marked, container);
dfs(i, j-1, board, str, marked, container);
dfs(i+1, j+1, board, str, marked, container);
dfs(i-1, j-1, board, str, marked, container);
dfs(i+1, j-1, board, str, marked, container);
dfs(i-1, j+1, board, str, marked, container);
marked[i][j] = false;
}
}
* @param word: a string word
* @return: the score of the word
*/
public int scoreOf(String word) {
if (!dic.contains(word))
return 0;
int len = word.length();
switch(len) {
case 0:
case 1:
case 2: return 0;
case 3: return 1;
case 4: return 1;
case 5: return 2;
case 6: return 3;
case 7: return 5;
default: return 11;
}
}
public static void main(String[] args) {
In in = new In(args[0]);
String[] dictionary = in.readAllStrings();
BoggleSolver solver = new BoggleSolver(dictionary);
BoggleBoard board = new BoggleBoard(args[1]);
int score = 0;
for (String word : solver.getAllValidWords(board)) {
StdOut.println(word);
score += solver.scoreOf(word);
}
StdOut.println("Score = " + score);
}
}
近期评论