Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Last active February 23, 2024 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenarBad/97b4b65e475bd236fdacb057538160ee to your computer and use it in GitHub Desktop.
Save LenarBad/97b4b65e475bd236fdacb057538160ee to your computer and use it in GitHub Desktop.
Word Boggle
public String[] wordBoggle(char board[][], String[] dictionary)
{
Set<String> doableWords = new HashSet<String>();
for (String word : dictionary) {
if (!doableWords.contains(word)) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (canMakeWord(i, j, word, 0, board)) {
doableWords.add(word);
}
}
}
}
}
String[] results = new String[doableWords.size()];
int i = 0;
for (String word : doableWords) {
results[i] = word;
i++;
}
return results;
}
private boolean canMakeWord(int i, int j, String str, int index, char[][] board) {
// checks
if (i < 0 || j < 0 || i == board.length || j == board[0].length) {
return false;
}
if (index == str.length()) {
return true;
}
if (board[i][j] != str.charAt(index) || board[i][j] == '+') {
return false;
}
char savedState = board[i][j];
board[i][j] = '+';
boolean result =
canMakeWord(i + 1, j, str, index + 1, board) || // d
canMakeWord(i, j + 1, str, index + 1, board) || // r
canMakeWord(i - 1, j, str, index + 1, board) || // u
canMakeWord(i, j - 1, str, index + 1, board) || // l
canMakeWord(i + 1, j + 1, str, index + 1, board) || // dr
canMakeWord(i - 1, j + 1, str, index + 1, board) || // ur
canMakeWord(i + 1, j - 1, str, index + 1, board) || // dl
canMakeWord(i - 1, j - 1, str, index + 1, board); // ul
board[i][j] = savedState;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment