public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0) {
return false;
}
boolean[][] visited = 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 (isExist(board, word, visited, i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean isExist(char[][] board, String word, boolean[][] visited, int i, int j, int pos) {
if (pos >= word.length()) {
return false;
}
if (i < 0 || i == board.length || j < 0 || j == board[0].length) {
return false;
}
if (word.charAt(pos) != board[i][j] || visited[i][j]) {
return false;
}
if (pos == word.length() - 1) {
return true;
}
visited[i][j] = true;
boolean result = isExist(board, word, visited, i + 1, j, pos + 1) || isExist(board, word, visited, i - 1, j, pos + 1) || isExist(board, word, visited, i, j + 1, pos + 1) || isExist(board, word, visited, i, j - 1, pos + 1);
visited[i][j] = false;
return result;
}
}
Word Search
最新推荐文章于 2018-03-15 12:40:13 发布