請(qǐng)?jiān)O(shè)計(jì)一個(gè)函數(shù)茄猫,用來判斷在一個(gè)矩陣中是否存在一條包含某字符串所有字符的路徑狈蚤。路徑可以從矩陣中的任意一格開始,每一步可以在矩陣中向左划纽、右脆侮、上、下移動(dòng)一格勇劣。如果一條路徑經(jīng)過了矩陣的某一格靖避,那么該路徑不能再次進(jìn)入該格子。例如比默,在下面的3×4的矩陣中包含一條字符串“bfce”的路徑(路徑中的字母用加粗標(biāo)出)幻捏。
[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]
但矩陣中不包含字符串“abfb”的路徑,因?yàn)樽址牡谝粋€(gè)字符b占據(jù)了矩陣中的第一行第二個(gè)格子之后命咐,路徑不能再次進(jìn)入這個(gè)格子篡九。
示例 1:
輸入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
輸出:true
示例 2:
輸入:board = [["a","b"],["c","d"]], word = "abcd"
輸出:false
提示:
1 <= board.length <= 200
1 <= board[i].length <= 200
參考
利用深度優(yōu)先和回溯法
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
const rowNum = board.length;
const colNum = board[0].length;
for (let i = 0; i < rowNum; ++i) {
for (let j = 0; j < colNum; ++j) {
if (board[i][j] === word[0]) {
const isExist = __exist(board, word, i, j, {});
if (isExist) return true; // 找到就返回
}
}
}
return false;
};
/**
* @param {character[][]} board
* @param {string} word
* @param {number} row
* @param {number} col
* @param {object} visited
* @return {boolean}
*/
function __exist(board, word, row, col, visited) {
// 單詞中字母全部匹配,說明可以搜索到侈百,返回true
if (!word.length) {
return true;
}
const key = `${row}-${col}`;
// 越界瓮下、之前訪問過翰铡、單詞首字母和當(dāng)前元素不相同钝域,返回false
if (
row >= board.length ||
row < 0 ||
col >= board[0].length ||
col < 0 ||
visited[key] ||
board[row][col] !== word[0]
) {
return false;
}
visited[key] = true;
word = word.slice(1);
// 下、上锭魔、右例证、左搜索(順序不重要)
const success =
__exist(board, word, row + 1, col, visited) ||
__exist(board, word, row - 1, col, visited) ||
__exist(board, word, row, col + 1, visited) ||
__exist(board, word, row, col - 1, visited);
// success為false時(shí),就是回溯
visited[key] = success;
return success;
}