矩阵中的路径
题目描述:
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如
[ a b c e]
[ s f c s]
[ a d e e]
矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
代码展示:
function hasPath(matrix, rows, cols, path)
{
// write code here
//dfs 的模版
//dfs(){
// 第一步,检查下标
// 第二步:检查是否被访问过,或者是否满足当前匹配条件
// 第三步:检查是否满足返回结果条件
// 第四步:都没有返回,说明应该进行下一步递归
// 标记
// dfs(下一次)
// 回溯
// }
// int main() {
// dfs(0, 0);
// }
//初始值判定
if(!matrix || !rows || !cols || rows*cols < path.length || path.length == 0){
return false;
}
//每一个点都可能是起点
var copy = matrix.split('');//数组
for(var i = 0; i < rows; i++){
for(var j = 0; j < cols; j++){
if(dfs(matrix, i, j, rows, cols, copy, path, 0)){
return true;
}
}
}
return false;
}
//dfs
function dfs(matrix, i, j, rows, cols, copy, path, k){
var index = i*cols + j;
//判断路径
if(i < 0 || j < 0 || i>=rows||j>=cols||path[k] != matrix[index]||copy[index]==true){
return false;
}
if(k == path.length - 1){
return true;
}
copy[index] = true;
if(dfs(matrix,i-1,j,rows,cols,copy,path,k+1)||
dfs(matrix,i+1,j,rows,cols,copy,path,k+1)||
dfs(matrix,i,j-1,rows,cols,copy,path,k+1)||
dfs(matrix,i,j+1,rows,cols,copy,path,k+1)){
return true;
}
copy[index] = false;
return false;
}