【Leetcode 346/700】79. 單詞搜尋 【中等】 回溯深度搜尋JavaScript版
1.題目
n 二維字元網格 board 和一個字串單詞 word 。如果 word 存在於網格中,返回 true ;否則,返回 false 。
單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母不允許被重複使用。
示例 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 僅由大小寫英文字母組成
2解題思路
1.遍歷 board 所有元素,找到 word的第一個相同的元素,並且進行標記 (marked),進入遞迴去找接下來的第二個字元,接著第三個字母。如果沒找到,返回 false;
- 在設定的邊界內進行回溯搜尋,即上下左右進行搜尋下一個字元。找到了進入新的遞迴,沒有找到的話,直接返回false;
3.解題注意點
1.及時進行標記字元的狀態,是已經訪問了,還是未訪問;
2.如果最後所有的字串擷取完了,說明已經找到符合的答案啦,直接返回true;
4.解題程式碼
/**
* @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