给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
class Solution {
boolean[][] visited;
char[][] board;
boolean res = false;
int[][] direction = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
String word;
int rows;
int cols;
public boolean exist(char[][] board, String word) {
this.word = word;
rows = board.length;
cols = board[0].length;
this.visited = new boolean[rows][cols];
this.board = board;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(board[i][j] == word.charAt(0)) {
dfs(i, j, 1);
}
}
}
return res;
}
private void dfs(int row, int col, int len) {
// 当判断len的长度等于word.length说明全部判断完成
if(len == word.length()) {
res = true;
return;
}
visited[row][col] = true;
// 对四个方位进行判断是否有符合下一个的字符
for (int k = 0; k < 4; k++) {
int newX = row + direction[k][0];
int newY = col + direction[k][1];
if (res == false && inArea(newX, newY) && !visited[newX][newY] && board[newX][newY] == word.charAt(len)) {
dfs(newX, newY, len + 1);
}
}
// 每一次进来都是新的起点, 需要对方位过得点进行恢复
visited[row][col] = false;
}
private boolean inArea(int x, int y) {
return x >= 0 && x < rows && y >= 0 && y < cols;
}
}
提示:
board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。