public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
int m = board.length, n = board[0].length;
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (helper(board, visited, word, 0, i, j)) {
return true;
}
}
}
return false;
}
private boolean helper(char[][] board, boolean[][] visited, String word, int pos, int i, int j) {
if (pos == word.length()) {
return false;
}
if (i < 0 || i == board.length || j < 0 || j == board[0].length) {
return false;
}
if (visited[i][j] || board[i][j] != word.charAt(pos)) {
return false;
}
if (pos + 1 == word.length()) {
return true;
}
visited[i][j] = true;
boolean flag = helper(board, visited, word, pos + 1, i + 1, j) || helper(board, visited, word, pos + 1, i - 1, j) || helper(board, visited, word, pos + 1, i, j + 1) || helper(board, visited, word, pos + 1, i, j - 1);
visited[i][j] = false;
return flag;
}
}
Word Search
最新推荐文章于 2022-11-28 20:15:08 发布