回溯法的应用:多个路径的情况
回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择
,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。
1、题目
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如
矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
2、解题
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if(matrix == NULL || str == NULL || rows<1 ||cols<1)return false;
bool* flag = (bool*)malloc(sizeof(bool)*(rows*cols));
memset(flag,0,sizeof(bool)*(rows*cols));
for(int i = 0;i<rows;i++){
for(int j = 0;j<cols;j++){
if(hasPathCore(matrix,rows,cols,i,j,str,flag) == true){
return true;
}
}
}
free(flag);
return false;
}
//判断某一个节点开始是否右相同的路径
bool hasPathCore(char* matrix, int rows, int cols, int i,int j,char* str,bool* flag){
//字符串结束,返回
if(*str == '\0')return true;
//横坐标超出限制
if(i<0 || i>= rows)return false;
//纵坐标超出限制
if(j<0 || j>=cols)return false;
//该节点已经走过了
if(flag[cols*i+j] == true)return false;
//该字符与当前节点不等
if(*str != matrix[cols*i+j])return false;
//判断下一个字符串
flag[cols*i+j] = true;
bool hasPath = true;
bool up = hasPathCore(matrix,rows,cols,i-1,j,str+1,flag);
bool down = hasPathCore(matrix,rows,cols,i+1,j,str+1,flag);
bool left = hasPathCore(matrix,rows,cols,i,j-1,str+1,flag);
bool right = hasPathCore(matrix,rows,cols,i,j+1,str+1,flag);
hasPath = up || down || left || right;
//没有可达的路径,标志恢复
if(hasPath == false){
flag[cols*i+j] = false;
}
return hasPath;
}
};
3、题目变形
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
4、变形解题
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
bool* flag = (bool*)malloc(sizeof(bool)*(rows*cols));
for(int i = 0;i<rows*cols;i++){
flag[i] = false;
}
int count = GetPathCount(threshold,rows,cols,0,0,flag);
free(flag);
return count;
}
//得到能到达的格子
int GetPathCount(int sum,int rows,int cols,int i,int j,bool* flag){
//超出范围
if(i>=rows || i<0 || j>=cols || j<0)return 0;
//已经遍历过
if(flag[cols*i+j] == true)return 0;
//数字之和大于k
if(JudgePortSum(sum,i,j)==false)return 0;
//尽可能到达的位置
flag[cols*i+j] = true;
int count = 1+GetPathCount(sum,rows,cols,i-1,j,flag)
+GetPathCount(sum,rows,cols,i+1,j,flag)
+GetPathCount(sum,rows,cols,i,j-1,flag)
+GetPathCount(sum,rows,cols,i,j+1,flag);
return count;
}
//判断坐标之和
bool JudgePortSum(int num,int x,int y){
int sum = 0;
while(x>0){
sum += x%10;
x /= 10;
}
while(y>0){
sum += y%10;
y /= 10;
}
if(num<sum)return false;
return true;
}
};