DFS, 这个里面搞了一个boolean二维数组,来记录该path是否已经经过该字母。
注意上下左右的边界条件。
public boolean exist(char[][] board, String word) {
int height = board.length;
int width = board[0].length;
boolean[][] visited = new boolean[height][width];
for (int i = 0; i < height; i++){
for (int j = 0; j < width; j++){
if (search(board,visited, i, j, word, 0)) {
return true;
}
}
}
return false;
}
private boolean search(char[][] board, boolean[][] visited,int row, int col,
String word, int index){
if (word.charAt(index) != board[row][col]) {
return false;
}
if (index == word.length() - 1) {
return true;
}
int height = board.length;
int width = board[0].length;
visited[row][col] = true;
//up
if (row > 0 && !visited[row - 1][col]
&& search(board, visited, row - 1, col, word, index + 1)){
return true;
}
//down
if (row < height - 1 && !visited[row + 1][col]
&& search(board, visited, row + 1, col, word, index +1)) {
return true;
}
//left
if (col > 0 && !visited[row][col - 1]
&& search(board, visited, row, col - 1, word, index + 1)){
return true;
}
//right
if (col < width - 1 && !visited[row][col+1]
&& search(board, visited, row, col + 1, word, index + 1)){
return true;
}
// if we did not find the path we need set this position as unvisited
visited[row][col] = false;
return false;
}
If we can use the the letters multiple times, then the code can be like this.
//Using more than once
public static boolean existDup(char[][] board, String word) {
for (int i=0; i<board.length; i++) {
for (int j=0; j<board[0].length; j++) {
if (board[i][j] == word.charAt(0)) {
if (helperDup(board, word.substring(1), i, j))
return true;
}
}
}
return false;
}
private static boolean helperDup(char[][] board, String tempWord, int row, int col) {
if (tempWord.length() == 0) return true;
//Stay the same place
if (board[row][col] == tempWord.charAt(0)) {
if (helperDup(board, tempWord.substring(1), row, col)) {
return true;
}
}
//Go LEFT
if (row > 0 && board[row - 1][col] == tempWord.charAt(0)) {
if (helperDup(board, tempWord.substring(1), row-1, col))
return true;
}
//Go RIGHT
if (row <board.length-1 && board[row + 1][col] == tempWord.charAt(0)) {
if (helperDup(board, tempWord.substring(1), row+1, col))
return true;
}
//Go UP
if (col > 0 && board[row][col-1] == tempWord.charAt(0)) {
if (helperDup(board, tempWord.substring(1), row, col-1))
return true;
}
//Go DOWN
if (col < board[0].length - 1 && board[row][col+1] == tempWord.charAt(0)) {
if (helper(board, tempWord.substring(1), row, col+1))
return true;
}
return false;
}
No comments:
Post a Comment