Word Search 08/07
Example
[
"ABCE",
"SFCS",
"ADEE"
]public class Solution {
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
private static int[] xPositon = {0,1,0,-1};
private static int[] yPositon = {1,0,-1,0};
public boolean exist(char[][] board, String word) {
// write your code here
if(board == null || board.length == 0 || board[0].length == 0 ){
return false;
}
boolean[][] isVisited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length ;++i ){
for(int j = 0; j < board[0].length;++j){
if(board[i][j] != word.charAt(0)){
continue;
}
isVisited[i][j] =true;
if(dfs(i,j,isVisited,word,1,board)){
return true;
}
}
}
return false;
}
public boolean dfs(int i, int j, boolean[][] isVisited,String word,int pos,char[][] board){
if(pos == word.length()){
return true;
}
for(int k = 0; k < 4; ++k){
int x = i + xPositon[k];
int y = j + yPositon[k];
if(!isGood(isVisited,word,x,y,pos,board)){
continue;
}
isVisited[x][y] = true;
if(dfs(x,y,isVisited,word,pos+1,board)){
return true;
}
isVisited[x][y] = false;
}
return false;
}
public boolean isGood(boolean[][] isVisited,String word,int x,int y,int pos,char[][]board){
if(x <0 || x >= board.length || y < 0 || y >= board[0].length || isVisited[x][y]|| board[x][y] != word.charAt(pos)){
return false;
}
return true;
}
}Last updated