题目
解题:回溯
// javascript
var exist = function(board, word) {
if (word.length === 0) return false;
const r = board.length, c = board[0].length;
const visited = new Array(r).fill(false).map(() => new Array(c).fill(false));
const directions = [[0, -1], [0, 1], [-1, 0], [1, 0]];
const check = (i, j, s, k) => {
if (board[i][j] !== s[k]) return false;
if (k === s.length - 1) return true;
visited[i][j] = true;
let result = false;
for (const [movei, movej] of directions) {
const newi = i + movei, newj = j + movej;
// 下标未超出界限 且 元素未被访问过
if (newi >= 0 && newi < r && newj >= 0 && newj < c && !visited[newi][newj]) {
if (check(newi, newj, s, k + 1) === true) {
result = true;
break;
}
}
}
// 回溯
visited[i][j] = false;
return result;
};
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
if (check(i, j, word, 0) === true) {
return true;
}
}
}
return false;
};