Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example, given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
Java Solution
This problem can be solve by using a typical DFS algorithm.
public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; boolean result = false; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(dfs(board,word,i,j,0)){ result = true; } } } return result; } public boolean dfs(char[][] board, String word, int i, int j, int k){ int m = board.length; int n = board[0].length; if(i<0 || j<0 || i>=m || j>=n){ return false; } if(board[i][j] == word.charAt(k)){ char temp = board[i][j]; board[i][j]='#'; if(k==word.length()-1){ return true; }else if(dfs(board, word, i-1, j, k+1) ||dfs(board, word, i+1, j, k+1) ||dfs(board, word, i, j-1, k+1) ||dfs(board, word, i, j+1, k+1)){ return true; } board[i][j]=temp; } return false; } |
Similarly, below is another way of writing this algorithm.
public boolean exist(char[][] board, String word) { for(int i=0; i<board.length; i++){ for(int j=0; j<board[0].length; j++){ if(dfs(board, word, i, j, 0)){ return true; } } } return false; } public boolean dfs(char[][] board, String word, int i, int j, int k){ if(board[i][j]!=word.charAt(k)){ return false; } if(k>=word.length()-1){ return true; } int[] di={-1,0,1,0}; int[] dj={0,1,0,-1}; char t = board[i][j]; board[i][j]='#'; for(int m=0; m<4; m++){ int pi=i+di[m]; int pj=j+dj[m]; if(pi>=0&&pi<board.length&&pj>=0&&pj<board[0].length&&board[pi][pj]==word.charAt(k+1)){ if(dfs(board,word,pi,pj,k+1)){ return true; } } } board[i][j]=t; return false; } |
ok why are you doing this and that man
it means that you’ve reached the end of the word, and therefore you have found a path through the grid.
y65y54y
Is there any advantage of using DFS here over BFS other than DFS is easier to implement with backtracking?
Why is the following check being done?
if(k==word.length()-1){
return true;
}
Sorry got it
ABCCEDFB?–> should not be found
public boolean dfs(char[][] board, String word, int i, int j, int k){
int m = board.length;
int n = board[0].length;
if(i<0 || j=m || j>=n){
return false;
}
if(board[i][j] == word.charAt(k)){
board[i][j]=’#’;
if(k==word.length()-1){
return true;
}else if(dfs(board, word, i-1, j, k+1)
||dfs(board, word, i+1, j, k+1)
||dfs(board, word, i, j-1, k+1)
||dfs(board, word, i, j+1, k+1)){
return true;
}
board[i][j]=word.charAt(k);
}
return false;
}