给定一个 2D 字符板和一个单词,判断该单词是否存在于网格中。该单词可以通过顺序相邻的单元格中的字母构成,其中“相邻”单元格是水平或垂直相邻的单元格。
解释: 这需要使用带有回溯的深度优先搜索(DFS)。遍历每个单元格。如果一个单元格与单词的第一个字母匹配,则开始 DFS。DFS 函数检查邻居,确保它们与下一个字母匹配并且在当前路径中尚未访问过。如果路径失败,通过取消标记单元格进行回溯。
function exist(board, word) {
const rows = board.length;
const cols = board[0].length;
function dfs(r, c, index) {
if (index === word.length) return true; // 找到单词
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== word[index]) {
return false;
}
const temp = board[r][c];
board[r][c] = '#'; // 标记为已访问
const found = dfs(r + 1, c, index + 1) ||
dfs(r - 1, c, index + 1) ||
dfs(r, c + 1, index + 1) ||
dfs(r, c - 1, index + 1);
board[r][c] = temp; // 回溯
return found;
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (board[r][c] === word[0] && dfs(r, c, 0)) {
return true;
}
}
}
return false;
}
const board = [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']];
console.log(exist(board, 'ABCCED')); // true
console.log(exist(board, 'SEE')); // true
console.log(exist(board, 'ABCB')); // false