Word Search
Description
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.
Constraints:
board
andword
consists only of lowercase and uppercase English letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
Solution(javascript)
const exist = (board = [], word) => {
if (board.length === 0) {
return false
}
const columnLength = board.length
const rowLength = board[0].length
const aux = (rowIndex = 0, columnIndex = 0, index = 0) => {
if (
rowIndex > rowLength - 1
|| columnIndex > columnLength - 1
|| columnIndex < 0
|| rowIndex < 0
|| index > word.length - 1
|| board[columnIndex][rowIndex] !== word[index]
) {
return false
}
if (board[columnIndex][rowIndex] === word[index] && index === word.length - 1) {
return true
}
const temp = board[columnIndex][rowIndex]
board[columnIndex][rowIndex] = undefined
const result = aux(rowIndex, columnIndex - 1, index + 1)
|| aux(rowIndex, columnIndex + 1, index + 1)
|| aux(rowIndex + 1, columnIndex, index + 1)
|| aux(rowIndex - 1, columnIndex, index + 1)
board[columnIndex][rowIndex] = temp
return result
}
for (let i = 0; i < columnLength; i++) {
for (let j = 0; j < rowLength; j++) {
if (aux(j, i, 0)) {
return true
}
}
}
return false
}