矩阵中的路径 剑指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; }
相关文章推荐
- 剑指offer65:矩阵中的路径
- 剑指Offer_65_矩阵中的路径
- 剑指offer-65题 矩阵中的路径
- 剑指offer 65 矩阵中的路径
- (C++)剑指offer-65:矩阵中的路径(回溯法)(没细看)
- 【每天一道剑指offer】2:矩阵中的路径
- 剑指offer — 矩阵中的路径
- 剑指offer(C++)——矩阵中的路径
- [剑指offer]矩阵中的路径
- 剑指offer:矩阵中的路径(考点:回溯法)
- 剑指offer | 训练题64:矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指Offer面试题66:矩阵中的路径 java实现
- 剑指offer-矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指Offer(12)矩阵中的路径
- 【剑指offer】面试题12:矩阵中的路径
- [剑指offer]矩阵中的路径
- 【剑指Offer学习】【面试题66:矩阵中的路径】
- 剑指offer面试题12:矩阵中的路径(java实现)