矩阵中的路径 剑指offer65题
include "stdafx.h"
include
include
include
include
include
using namespace std;
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
vector<vector
vector<vector
vector
for (int i = 0;i < rows;i++)
{
for (int j = 0;j < cols;j++)
{
mat[i][j] =matrix[ i*cols + j];
}
}
for (int i = 0;i < strlen(str);i++)
{
s.push_back(str[i]);
}
bool flag = false;
for (int i = 0;i < rows;i++)
{
for (int j = 0;j < cols;j++)
{
if (mat[i][j] == str[0])
{
if (getPath(mat, i, j, s, 0, visited) == true)
{
flag = true;
break;
}
}
if (flag == true)
{
break;
}
}
}
return flag;
}
bool getPath(vector<vector
{
if (num == s.size() - 1 && mat[rows][cols] == s[num])
return true;
if (mat[rows][cols] == s[num])
{
visited[rows][cols] = true; //已经被访问
num++;
bool left = false;
bool right = false;
bool up = false;
bool down = false;
//向左走
if (cols - 1 >= 0 && visited[rows][cols - 1] == false)
left = getPath(mat, rows, cols - 1, s, num, visited);
//向右走
if (cols + 1 < mat[0].size() && visited[rows][cols + 1] == false)
right = getPath(mat, rows, cols + 1, s, num, visited);
//向上走
if (rows - 1 >= 0 && visited[rows - 1][cols] == false)
up = getPath(mat, rows - 1, cols, s, num, visited);
//向下走
if (rows + 1 < mat.size() && visited[rows + 1][cols] == false)
down = getPath(mat, rows + 1, cols, s, num, visited);
visited[rows][cols] = false;
return left || right || up || down;
}
else
{
return false;
}
}
};
int main()
{
Solution s;
cout << s.hasPath("ABCESFCSADEE", 3, 4, "ABCCED") << endl;
return 0;
}

浙公网安备 33010602011771号