- Word Search
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
var exist = function (board, word) {
const directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]
let result = false
function back(i, x, y) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) {
return
}
const c = board[x][y]
if (c != word[i]) {
return
}
if (i == word.length - 1) {
result = true
return
}
board[x][y] = '#'
for (let d of directions) {
back(i + 1, x + d[0], y + d[1])
}
board[x][y] = c
}
for (let x = 0; x < board.length; x++) {
for (let y = 0; y < board[0].length; y++) {
back(0, x, y)
}
}
return result
};