Skip to content

Instantly share code, notes, and snippets.

@logicmd
Created December 11, 2012 17:30
Show Gist options
  • Save logicmd/4260482 to your computer and use it in GitHub Desktop.
Save logicmd/4260482 to your computer and use it in GitHub Desktop.
Word Search
public class Solution {
public static void main(String args[]){
System.out.println("Hello world");
new java.util.Scanner(System.in).nextLine();
}
public boolean exist(char[][] board, String word) {
// Start typing your Java solution below
// DO NOT write main() function
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
if(board[i][j]==word.charAt(0)) {
return find(board, i, j, word.substring(1));
}
}
}
}
public boolean find(char[][] board, int i, int j, String word) {
boolean flag = word.length == 1 ? true : false;
if( i-1 >= 0 && board[i-1][j] == word.charAt(0) ) {
return flag || find(board, i-1, j, word.substring(1));
}
if( i+1 < board.length && board[i+1][j] == word.charAt(0) ) {
return flag || find(board, i+1, j, word.substring(1));
}
if( j+1 < board[i].length && board[i][j+1] == word.charAt(0) ) {
return flag || find(board, i, j+1, word.substring(1));
}
if( j-1 >= 0 && board[i][j-1] == word.charAt(0) ) {
return flag || find(board, i, j-1, word.substring(1));
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment