剑指offer——13矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
 
题解:
  使用回溯法,进行深度遍历,并设置一个visit来标记时候遍历过
 
  
 class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if (matrix == nullptr || rows < || cols < )return false;
if (str == nullptr)return true;
vector<bool>visit(rows*cols, false);
int pot = ;
for (int i = ; i < rows; ++i)
for (int j = ; j < cols; ++j)
if (DFS(matrix, rows, cols, i, j, visit, str, pot))
return true;
return false;
}
bool DFS(const char* matrix, const int rows, const int cols,int i, int j, vector<bool>&visit,const char *str, int &pot)
{
if (str[pot] == '\0')return true;
bool flag = false;
if (i >= && i < rows && j >= && j < cols &&
matrix[i*cols + j] == str[pot] && visit[i*cols + j] == false)
{
++pot;
visit[i*cols + j] = true;
flag = DFS(matrix, rows, cols, i + , j, visit, str, pot) ||
DFS(matrix, rows, cols, i - , j, visit, str, pot) ||
DFS(matrix, rows, cols, i, j + , visit, str, pot) ||
DFS(matrix, rows, cols, i, j - , visit, str, pot);
if (flag == false)
{
--pot;
visit[i*cols + j] = false;//回溯
}
}
return flag;
}
};
上一篇:NanUI for Winform 使用示例【第一集】——山寨个代码编辑器


下一篇:Prism&MEF构建开发框架 (三)