题目:设计一个函数,用来判断在一个矩阵中是否存在一条包含某字条串所有字条的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
此题与八皇后一样,是一道典型的“回溯法”应用题型。
参考作者的解题思想,给出自己的所写的代码:
#include<vector>
#include<iostream>
#include<string>
using namespace std;
bool hasPathCore(vector<vector<char>>& chs,
string& str, int& rows, int& cols, int r, int c, int& num,
vector<vector<bool>>& visited) {
if (num == str.size())//递归终止
return true;
bool hasPath = false;
if (r >= 0 && r < rows&&c >= 0 && c < cols&&chs[r][c] == str[num] && !visited[r][c]) {
++num;
visited[r][c] = true;
//以下进行上下左右递归遍历
hasPath = hasPathCore(chs, str, rows, cols, r - 1, c, num, visited) ||
hasPathCore(chs, str, rows, cols, r + 1, c, num, visited) ||
hasPathCore(chs, str, rows, cols, r, c - 1, num, visited) ||
hasPathCore(chs, str, rows, cols, r, c+1, num, visited);
if (!hasPath) {//如果没有找着,则回溯
num--;
visited[r][c] = false;
}
}
return hasPath;
}
bool hasPath(vector<vector<char>>& chs, string& str) {
int rows = chs.size();
if (rows == 0)
return false;
int cols = chs[0].size();
int num = 0;
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c)
if (hasPathCore(chs, str, rows, cols, r, c, num, visited))
return true;
return false;
}