Skip to content

Instantly share code, notes, and snippets.

@pepe-romeros
Created November 16, 2016 20:24
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 pepe-romeros/12cbfe4e9624a87fa880ab810e99daeb to your computer and use it in GitHub Desktop.
Save pepe-romeros/12cbfe4e9624a87fa880ab810e99daeb to your computer and use it in GitHub Desktop.
public class BoggleSolution {
private static int dictionarySize = 0;
private static int boggleCols = 0;
private static int boggleRows = 0;
private static String[] dictionary = {"GEEKS", "FOR", "QUIZ", "GO"};
private static boolean isWord(String str) {
for(int i = 0; i < dictionarySize; i++) {
if(str.equals(dictionary[i])){
return true;
}
}
return false;
}
private static void findWordsUtil(char[][] boggle, boolean[][] visited, int i, int j, String str) {
// Mark current cell as visited and append current character to str
visited[i][j] = true;
str = str + boggle[i][j];
// If str is present in dictionary, then print it
if (isWord(str))
System.out.println(str);
// Traverse adjacent cells of boggle[i][j]
for (int row=i-1; row<=i+1 && row<boggleRows; row++)
for (int col=j-1; col<=j+1 && col<boggleCols; col++)
if (row>=0 && col>=0 && !visited[row][col])
findWordsUtil(boggle,visited, row, col, str);
// Erase current character from string and mark visited of current cell as false
str = str.substring(0, str.length()-1);
visited[i][j] = false;
}
private static void findWords(char[][] boggle) {
dictionarySize = dictionary.length;
boggleCols = boggle.length;
boggleRows = boggle[0].length;
// Mark all characters as not visited
boolean visited[][] = new boolean[boggleRows][boggleCols];
// Initialize current string
String str = "";
// Consider every character and look for all words
// starting with this character
for (int i=0; i<boggleRows; i++)
for (int j=0; j<boggleCols; j++)
findWordsUtil(boggle, visited, i, j, str);
}
public static void main(String[] args) {
char boggle[][] = {{'G','I','Z'},
{'U','E','K'},
{'Q','S','E'}};
findWords(boggle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment