题解 | #矩阵中的路径#
矩阵中的路径
http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
// index表示当前正在找的字符串字符的索引
function dfs (matrix, wordArr, i, j, index) {
// 超出矩阵的范围
if (i < 0 || j < 0 || i > matrix.length - 1 || j > matrix[0].length - 1) {
return false
}
// 矩阵当前元素与字符串当前字符不匹配
if (matrix[i][j] !== wordArr[index]) {
return false
}
// 找到所给路径
if (index == wordArr.length - 1) {
return true
}
let choice = matrix[i][j]
// 表示这里选过了
matrix[i][j] = '*'
let res =
dfs(matrix, wordArr, i, j - 1, index + 1) ||
dfs(matrix, wordArr, i, j + 1, index + 1) ||
dfs(matrix, wordArr, i - 1, j, index + 1) ||
dfs(matrix, wordArr, i + 1, j, index + 1)
matrix[i][j] = choice
return res
}
function hasPath( matrix , word ) {
// write code here
let wordArr = word.split('')
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
if (dfs(matrix, wordArr, i, j, 0)) {
return true
}
}
}
return false
}
module.exports = {
hasPath : hasPath
};