题目描述 (来自牛客网)
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
不用太纠结矩阵的形状,访问其中的元素用 [rows*col + col] 下标的计算不要出错!! (一维)即可。
从矩阵的每个元素开始做 遍历。 遍历的时候,如果满足边界条件并且当前str元素和矩阵对应的元素(矩阵的元素只能走上或下或左或右)相等,接着遍历下一个。
回溯(和深搜差不多)要注意终止的条件。
memset 的用法:https://blog.csdn.net/dan15188387481/article/details/49621447
注意函数传入的是字符指针,用法:
http://www.runoob.com/w3cnote/cpp-string-array-pointer.html
关于 **new 和 delete **:
https://www.cnblogs.com/hazir/p/new_and_delete.html
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if(matrix==nullptr || rows<1 || cols<1 || str==nullptr)return false;
bool *visited = new bool[rows*cols];
memset(visited,0,sizeof(bool)*(rows*cols));
int p_str = 0;
for (int i=0;i<rows;i++)
{
for (int j = 0;j<cols;j++)
{
if (hp(i,j,rows,cols,p_str,visited,matrix,str))
{
return true;
}
}
}
delete[] visited;
return false;
}
bool hp(int row,int col,int rows,int cols,int& p,bool* v,char* matrix,char* str)
{
if (str[p]=='\0')
{
return true;
}
bool ans = false;
if (row>=0 && row<rows && col>=0 && col<cols && !v[row*cols+col] &&
matrix[row*cols+col]==str[p])
{
p++;
v[row*cols+col] = true;
ans = hp(row+1,col,rows,cols,p,v,matrix,str)
|| hp(row,col-1,rows,cols,p,v,matrix,str)
|| hp(row,col+1,rows,cols,p,v,matrix,str)
|| hp(row-1,col,rows,cols,p,v,matrix,str);
if (ans) return true;
p--;
v[row*cols+col] = false;
}
return ans;
}
};
在牛客上看了更简洁的一些的:
bool solver(char* matrix,int r,int c,int rows,int cols,char* str,int k,bool *vis)
{
int index = r*cols+c;
if ( r<0 || r>=rows || c<0 || c>=cols || vis[index] || matrix[index] != str[k] )return false;
//if (str[k]=='\0')return true;
if ( k == strlen(str)-1)return true;
vis[index]=true;
if (solver(matrix,r-1,c,rows,cols,str,k+1,vis) || solver(matrix,r+1,c,rows,cols,str,k+1,vis)
|| solver(matrix,r,c+1,rows,cols,str,k+1,vis) || solver(matrix,r,c-1,rows,cols,str,k+1,vis))
return true;
vis[index]=false;
return false;
}
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
同样是回溯(深搜)
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
bool *visited = new bool[rows*cols];
memset(visited,0,sizeof(bool)*rows*cols);
int ans = 0;
dfs(0,0,rows,cols,ans,threshold,visited);
return ans;
}
void dfs(int row,int col,int rows,int cols,int& ans,int threshold,bool* v)
{
if (row<0 || row>=rows || col<0 || col>=cols || v[row*cols+col])
{
return ;
}
int tmp = my_sum(row)+my_sum(col);
if (tmp<=threshold)
{
ans++;
v[cols*row+col] = 1;
dfs(row+1,col,rows,cols,ans,threshold,v);
dfs(row,col+1,rows,cols,ans,threshold,v);
dfs(row-1,col,rows,cols,ans,threshold,v);
dfs(row,col-1,rows,cols,ans,threshold,v);
}
return;
}
int my_sum(int n)
{
int ans = 0;
while (n)
{
ans += (n%10);
n /= 10;
}
return ans;
}
};