Leetcode---剑指Offer题12 13---回溯法
剑指Offer-面试题12---回溯法
1、题目1 矩阵中的路径
https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/submissions/
回溯法
class Solution {
public:
bool searchPath(const vector<vector<char>>& board,int i,int j,const string& word,int index,int height,int width,int len,vector<bool> searched)
{
if(index >= len)
return true;
if(i>=height || j>=width || i<0 || j<0 || board[i][j]!=word[index] || searched[j+i*width])
{
return false;
}
bool isCanGo = false;
searched[j+i*width] = true;
index++;
isCanGo = searchPath(board,i+1,j,word,index,height,width,len,searched)||
searchPath(board,i-1,j,word,index,height,width,len,searched)||
searchPath(board,i,j+1,word,index,height,width,len,searched)||
searchPath(board,i,j-1,word,index,height,width,len,searched);
//不能成功的话,回溯寻找新的路径
if(!isCanGo)
{
index -- ;
searched[j+i*width] = false;
}
return isCanGo;
}
bool exist(vector<vector<char>>& board, string word)
{
if(board.size()==0 || word==" ")
return false;
int len = word.size();
int height = board.size();
int width = board[0].size();
vector<bool> searched(height*width,false);
for(int i=0; i<height; i++)
{
for(int j=0; j<width; j++)
{
if(searchPath(board,i,j,word,0,height,width,len,searched))
return true;
}
}
return false;
}
};
2、题目2 机器人的运动范围
https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/
回溯法
class Solution {
public:
int movingCount(int m, int n, int k)
{
if(m <= 0 || n<=0 || k < 0)
return 0;
vector<bool> hasGo(m*n,false);
int result = searchPath(0,0,m,n,k,hasGo);
return result;
}
int CalculateNumWei(int num1,int num2)
{
int result = 0;
while(num1 != 0){
result += num1%10;
num1/=10;
}
while(num2 != 0){
result += num2%10;
num2/=10;
}
return result;
}
int searchPath(int i,int j,int m, int n, int k,vector<bool>& hasGo)
{
int count = 0;
if(i>=m || j>=n || i<0 || j<0 || CalculateNumWei(i,j)>k ||hasGo[j+i*n])
return count;
hasGo[j+i*n] = true;
count = 1 + searchPath(i+1,j,m,n,k,hasGo)+
searchPath(i-1,j,m,n,k,hasGo)+
searchPath(i,j+1,m,n,k,hasGo)+
searchPath(i,j-1,m,n,k,hasGo);
return count;
}
};