剑指 Offer 12. 矩阵中的路径
回溯法的经典习题,回溯法就是暴力法的升级版
#include <vector>
#include <iostream>
using namespace std;
//剑指 Offer 12. 矩阵中的路径
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
//初始化visited矩阵
vector<vector<bool>> visited;
visited.resize(board.size());
for (int i = 0; i < visited.size(); i++) {
visited[i].resize(board[0].size());
}
for (int i = 0; i < visited.size(); i++) {
for (int j = 0; j < visited[0].size(); j++) {
visited[i][j] = false;
}
}
//找所有可能的入口
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
//cout << "board[i][j] is " << board[i][j] << " " << "word[0] is " << word[0];
if (board[i][j] == word[0]) {
if (Exist_Core(board, i, j, visited, 1, word)) {
return true;
}
}
}
}
return false;
}
//负责递归的函数,exist函数里找好入口(就是符合第一个字母的起点),这里分别判断(row,col)的上下左右符合不符合(也包含了边界判断)
bool Exist_Core(vector<vector<char>>& board, int row, int col,
vector<vector<bool>>& visited, int Cur_Ind, string word) {
//Cur_Ind就是这次要判断第几个找不找得到
if (word.size() < Cur_Ind + 1) return true;
visited[row][col] = 1;
//上面
int NextRow = row - 1;
int NextCol = col;
if (BorJud(board, NextRow, NextCol) && (visited[NextRow][NextCol] != true)) {
if (board[NextRow][NextCol] == word[Cur_Ind]) {
if (Exist_Core(board, NextRow, NextCol, visited, Cur_Ind + 1, word)) {
return true;
}
}
}
//下面
NextRow = row + 1;
NextCol = col;
if (BorJud(board, NextRow, NextCol) && (visited[NextRow][NextCol] != true)) {
if (board[NextRow][NextCol] == word[Cur_Ind]) {
if (Exist_Core(board, NextRow, NextCol, visited, Cur_Ind + 1, word)) {
return true;
}
}
}
//左面
NextRow = row;
NextCol = col - 1;
if (BorJud(board, NextRow, NextCol) && (visited[NextRow][NextCol] != true)) {
if (board[NextRow][NextCol] == word[Cur_Ind]) {
if (Exist_Core(board, NextRow, NextCol, visited, Cur_Ind + 1, word)) {
return true;
}
}
}
//右面
NextRow = row;
NextCol = col + 1;
if (BorJud(board, NextRow, NextCol) && (visited[NextRow][NextCol] != true)) {
if (board[NextRow][NextCol] == word[Cur_Ind]) {
if (Exist_Core(board, NextRow, NextCol, visited, Cur_Ind + 1, word)) {
return true;
}
}
}
//失败
visited[row][col] = 0;
return false;
}
bool BorJud(vector<vector<char>>& board, int row, int col) {
int MatRows = board.size() - 1;
int MatClos = board[0].size() - 1;
if (MatRows < 0 || MatClos < 0) {
cout << "error border check!";
}
if ((row < 0) || (col < 0) || (row > MatRows) || (col > MatClos)) {
return false;
}
return true;
}
};
int main(void) {
Solution solution;
vector<vector<char>> board = { {'a','b','c','e'},
{'s','f','c','s'},
{'a','d','e','e'}};
string word = "bfce";
int res = solution.exist(board, word);
cout << res;
return 1;
}