【Leetcode 346/700】79. 单词搜索 【中等】 回溯深度搜索JavaScript版
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 仅由大小写英文字母组成
1.遍历 board 所有元素,找到 word的第一个相同的元素,并且进行标记 (marked),进入递归去找接下来的第二个字符,接着第三个字母。如果没找到,返回 false;
1.及时进行标记字符的状态,是已经访问了,还是未访问;
2.如果最后所有的字符串截取完了,说明已经找到符合的答案啦,直接返回true;
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function (board, word) {
let border = [[0, 1], [0, -1], [1, 0], [-1, 0]], //定义上下左右四个方向
col = board.length, //行数
row = board[0].length, //列数
marked = [...Array(col)].map(v => Array(row).fill()); //同行列空矩阵,用于记录已经访问的
//空数组直接返回false
if (!col) return false;
let backTracing = (i, j, markeds, boards, words) => {
//截取所有的字符,说明已经找到
if (!words.length) {
return true;
}
for (let p = 0; p < border.length; p++) {
let curi = i + border[p][0]; //左右方向
let curj = j + border[p][1]; //上下方向
//判断边界,且找到了第一个字符
if ((curi >= 0 && curi < col) && (curj >= 0 && curj < row && boards[curi][curj] == words[0])) {
//已经用过,直接跳过
if (markeds[curi][curj] == 1) {
continue
}
//标记为已使用
markeds[curi][curj] = 1;
//接着找下一个字符
if (backTracing(curi, curj, markeds, boards, words.substring(1))) {
return true
} else {
//使用完重置掉
markeds[curi][curj] = 0;
}
}
}
return false
}
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
if (board[i][j] === word[0]) {
//找到第一个字符,标记为已经使用
marked[i][j] = 1;
//进入回溯
if (backTracing(i, j, marked, board, word.substring(1))) {
return true
} else {
//重置状态
marked[i][j] = 0;
}
}
}
}
return false
};
//测试用例 1
let board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], word = "ABCCED";
//测试用例2
let board1 = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], word1 = "SEE"
//测试用例3
let board2 = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], word2 = "ABCB"
console.log(exist(board, word)) //true
console.log(exist(board1, word1)) //true
console.log(exist(board2, word2)) //false