For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
private static final int[][] direction = {{1,0},{-1,0},{0,1},{0,-1}};
public boolean exist(char[][] board,String word){
if(word == null || word.length() == 0){
return true;
}
if(board == null || board.length == 0 || board[0].length==0){
return false;
}
boolean[][] hasVisited = new boolean[board.length][board[0].length];
for(int r=0;r<board.length;r++){
for(int c=0;c<board[0].length;c++){
if(backtracking(0,r,c,hasVisited,board,word)){
return true;
}
}
}
return false;
}
private boolean backtracking(int curLen,int r,int c,boolean[][] visited,final char[][] board,final String word){
if(curLen == word.length()){
return true;
}
if(r<0||r>=board.length||c<0||c>=board[0].length || board[r][c]!=word.charAt(curLen)||visited[r][c]){
return false;
}
visited[r][c] = true;
for(int[] d :direction){
if(backtracking(curLen+1, r, c, visited, board, word)){
return true;
}
}
visited[r][c] = false;
return false;
}