给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private static int dx[] = {0, 1, 0, -1};
private static int dy[] = {1, 0, -1, 0};
public static boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
if (judge(board, i, j, new boolean[board.length][board[0].length], word, 0)) {
return true;
}
}
}
return false;
}
private static boolean judge(char[][] board, int x, int y, boolean[][] visited, String word, int index) {
if (board[x][y] != word.charAt(index)) {
return false;
}
if (index == word.length() - 1) {
return true;
}
visited[x][y] = true;
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length && !visited[nx][ny]) {
boolean next = judge(board, nx, ny, visited, word, index + 1);
if (next) {
return true;
}
}
}
visited[x][y] = false;
return false;
}
}