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.
Example 1:
Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true
DFS + 回溯,
1.选择起点,可以看出起点不止一个
2.下一个字符有可能在当前点的上下左右四个方向,判断这四个方向是否能走,判断一下该方向上的字符是否是word里的下一个字符,判断该字符是否已经访问过(使用visited数组保存每个点是否被访问)
3. 当四个方向都走不通,且此时的字符还不是目标值,代表此路不通
4. 回溯:当选点错误时,要撤销访问过这个点的痕迹,去尝试别的路线
var exist = function(board, word) {
let res = false;
let visited = [...Array(board.length)].map(() => Array(board[0].length).fill(0))
const dfs = (i, j, str, index) => {
if(str.length === word.length) {
if(str === word) {
res = true;
}
return;
}
if(i - 1 >= 0 && board[i - 1][j] === word[index + 1] && !visited[i - 1][j]) {
visited[i][j] = 1
dfs(i - 1, j, str + word[index + 1], index+1);
visited[i][j] = 0
}
if(i + 1 < board.length && board[i + 1][j] === word[index + 1] && !visited[i + 1][j]) {
visited[i][j] = 1
dfs(i + 1, j, str + word[index + 1], index+1);
visited[i][j] = 0
}
if(j - 1 >= 0 && board[i][j - 1] === word[index + 1] && !visited[i][j - 1]) {
visited[i][j] = 1
dfs(i, j - 1, str + word[index + 1], index+1);
visited[i][j] = 0
}
if(j + 1 < board[i].length && board[i][j + 1] === word[index + 1] && !visited[i][j + 1]) {
visited[i][j] = 1
dfs(i, j + 1, str + word[index + 1], index+1);
visited[i][j] = 0
}
}
for(let i = 0; i < board.length; i++) {
for(let j = 0; j < board[i].length; j++) {
if(board[i][j] === word[0]) {
dfs(i, j, word[0], 0)
}
}
}
return res
};