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
.
解题思路:
DP解法,可以用recursion. 每次从一个state 转换到另外一个state的时候,我们需要知道,当前的位置(x, y), 以及匹配word的位置 pos, 还有就是为了避免重复visit一个元素,我们得有一个visited数组来记录走过的路径。
Java Code:
public boolean exist(char[][] board, String word) {
int row = board.length;
int col = board[0].length;
boolean[] visited = new boolean[row*col];
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(board[i][j] == word.charAt(0) && search(board, i, j, visited, word, 0)){
return true;
}
}
}
return false;
}
public boolean search(char[][] board, int x, int y, boolean[] visited, String word, int pos){
if(pos == word.length() - 1){
return true;
}
int row = board.length;
int col = board[0].length;
if(x > 0 && !visited[(x-1)*col + y] && word.charAt(pos+1) == board[x-1][y]){
visited[x*col+y] = true;
if(search(board, x-1, y, visited, word, pos+1)){
return true;
}
visited[x*col+y] = false;
}
if(x+1 < row && !visited[(x+1)*col + y] && word.charAt(pos+1) == board[x+1][y]){
visited[x*col+y] = true;
if(search(board, x+1, y, visited, word, pos+1)){
return true;
}
visited[x*col+y] = false;
}
if(y > 0 && !visited[x*col + y - 1] && word.charAt(pos+1) == board[x][y-1]){
visited[x*col+y] = true;
if(search(board, x, y-1, visited, word, pos+1)){
return true;
}
visited[x*col+y] = false;
}
if(y+1 < col && !visited[x*col + y + 1] && word.charAt(pos+1) == board[x][y+1]){
visited[x*col+y] = true;
if(search(board, x, y+1, visited, word, pos+1)){
return true;
}
visited[x*col+y] = false;
}
return false;
}