Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created December 1, 2013 04:44
Show Gist options
  • Save charlespunk/7728593 to your computer and use it in GitHub Desktop.
Save charlespunk/7728593 to your computer and use it in GitHub Desktop.
public class Solution {
public boolean exist(char[][] board, String word) {
if(word.length() == 0) return true;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(exist(board, i, j, word, 0)) return true;
}
}
return false;
}
public boolean exist(char[][] board, int x, int y, String word, int index){
if(board[x][y] == word.charAt(index)){
if(index == word.length() - 1) return true;
char c = board[x][y];
board[x][y] = ' ';
if(x > 0 && exist(board, x - 1, y, word, index + 1)) return true;
if(x < board.length - 1 && exist(board, x + 1, y, word, index + 1)) return true;
if(y > 0 && exist(board, x, y - 1, word, index + 1)) return true;
if(y < board[0].length - 1 && exist(board, x, y + 1, word, index + 1)) return true;
board[x][y] = c;
return false;
}
else return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment