题解 | #矩阵中的路径#
矩阵中的路径
https://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) { 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, };