题解 | #矩阵中的路径#
矩阵中的路径
https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型二维数组
* @param word string字符串
* @return bool布尔型
*/
function hasPath( matrix , word ) {
// write code here
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
if(hasPathCache(matrix, word, i, j)) return true
}
}
return false
}
function hasPathCache(matrix, word, x, y) {
if (word.length === 0) return true
const currentWord = word[0]
const restltWord = word.slice(1)
if (x < 0 || y < 0 || x >= matrix.length || y >= matrix[0].length || matrix[x][y] !== currentWord) {
return false
}
const temp = matrix[x][y]
matrix[x][y] = '###'
let res = hasPathCache(matrix, restltWord, x - 1, y) || hasPathCache(matrix, restltWord, x, y + 1) || hasPathCache(matrix, restltWord, x + 1, y) || hasPathCache(matrix, restltWord, x, y - 1)
matrix[x][y] = temp
return res
}
module.exports = {
hasPath : hasPath
};

