/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param matrix char字符型二维数组 * @param word string字符串 * @return bool布尔型 */ function hasPath(matrix, word) { // write code here const dfs = (matrix, word, i, j, init) => { if ( i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length || matrix[i][j] !== word[init] ) { return false; } if (init === word.length - 1) return true; let temp = matrix[i][j]; // 保存棋盘位置 matrix[i][j] = "."; const res = dfs(matrix, word, i + 1, j, init + 1) || dfs(matrix, word, i, j + 1, init + 1) || dfs(matrix, word, i - 1, j, init + 1) || dfs(matrix, word, i, j - 1, init + 1); matrix[i][j] = temp; return res; }; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { if (dfs(matrix, word, i, j, 0)) return true; } } return false; } module.exports = { hasPath: hasPath, };