您的位置:首页 > Web前端

矩阵中的路径 剑指offer65题

2017-05-15 20:08 639 查看

include "stdafx.h"

#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
#include<stack>
using namespace std;

class Solution {
public:

bool hasPath(char* matrix, int rows, int cols, char* str)
{
vector<vector<bool>> visited(rows, vector<bool>(cols,false));
vector<vector<char>> mat(rows, vector<char>(cols, 'a'));
vector<char> s;
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<char>> mat, int rows, int cols, vector<char> s,int num, vector<vector<bool>> visited)
{
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: