1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| var problem = (board, target) => { const dx = [-1, 0, 1, 0] const dy = [0, 1, 0, -1] const rows = board.length const cols = board[0].length const visited = new Array(rows) .fill(0) .map(() => new Array(cols).fill(false))
function inArea(x, y) { return x >= 0 && x < rows && y >= 0 && y < cols }
for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) if (dfs(board, target, 0, i, j)) return true return false
function dfs (board, target, level, x, y) { if (level === target.length - 1) return board[x][y] === target[level]
if (board[x][y] !== word[level]) return false
visited[x][y] = true for (let i = 0; i < 4; i++) { const newX = x + dx[i] const newY = y + dy[i]
if (inArea(newX, newY) && !visited[newX][newY] && dfs(board, word, level + 1, newX, newY) ) return true } visited[x][y] = false } }
|