剑指offer——65.矩阵中的路径

来源:互联网 发布:tensor flow 知乎 编辑:程序博客网 时间:2024/06/18 04:57

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串”bcced”的路径,但是矩阵中不包含”abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

代码

思路:回溯法

function hasPathCore(matrix, rows, cols, row, col, path, pathIndex, visited) {  var hasPath = false;  if (row < rows && col < cols && row >= 0 && col >= 0 && visited[row][col] === false) {    if (matrix[row * cols + col] === path[pathIndex]) {      visited[row][col] = true;      if (pathIndex === path.length - 1) {        hasPath = true;      } else {        hasPath = hasPathCore(matrix, rows, cols, row - 1, col, path, pathIndex + 1, visited) ||                  hasPathCore(matrix, rows, cols, row + 1, col, path, pathIndex + 1, visited) ||                  hasPathCore(matrix, rows, cols, row, col - 1, path, pathIndex + 1, visited) ||                  hasPathCore(matrix, rows, cols, row, col + 1, path, pathIndex + 1, visited);        if (!hasPath) {          visited[row][col] = false;        }      }    }  }  return hasPath;}function hasPath(matrix, rows, cols, path){    // write code here    if (path.length <= 0) {      return true;    }    var visited = [];    var temp = [];    var i, j;    for (i = 0; i < rows; i++) {      temp = [];      for (j = 0; j < cols; j++) {        temp.push(false);      }      visited.push(temp);    }    for (i = 0; i < rows; i++) {      for (j = 0; j < cols; j++) {        if (hasPathCore(matrix, rows, cols, i, j, path, 0, visited)) {          return true;        }      }    }    return false;}
原创粉丝点击