【LeetCode热题100(58/100)】单词搜索
题目地址:链接
思路: 依然是简单的递归回溯
/*** @param {character[][]} board* @param {string} word* @return {boolean}*/
const DX = [0, 1, 0, -1];
const DY = [1, 0, -1, 0];
var exist = function(board, word) {let [n, m] = [board.length, board[0].length];let wordLen = word.length;let ans = false;let isVit;const dfs = (x, y, wordIdx) => {if(wordIdx == wordLen - 1 || ans) {ans = true;return;}if(board[x][y] !== word[wordIdx]) return;for(let i = 0; i < 4; i ++) {let [nx, ny] = [x + DX[i], y + DY[i]];if( 0 <= nx && nx < n && 0 <= ny && ny < m && !isVit[nx][ny] ) {if(board[nx][ny] == word[wordIdx + 1]) {isVit[nx][ny] = true;dfs(nx, ny, wordIdx + 1);isVit[nx][ny] = false;}}}}for(let i = 0; i < n; i ++) {for(let j = 0; j < m; j ++) {if(board[i][j] == word[0]) {isVit = Array.from({length: n}, () => new Array(m).fill(false));isVit[i][j] = true;dfs(i, j, 0);isVit[i][j] = false;}}}return ans;
};
