Matrix path
topic
Please design a function that determines whether there is a route that contains all the characters of a character string in a matrix.
A lattice path may start from any of the matrix, each step in the matrix can be left, right, up, down one grid.
If one path through the matrix of one grid, the following can not enter the grid again.
note:
- Input path is not empty;
- All the characters that appear are capital letters;
Sample
matrix= [
[“A”,“B”,“C”,“E”],
[“S”,“F”,“C”,“S”],
[“A”,“D”,“E”,“E”]
]str=“BCCE” , return “true”
str=“ASAE” , return “false”
answer
The title using the depth-first search traversal, in a given matrix, in order to enumerate each character string
note:
- In the deep search process, if dfs is true, then directly back
- That the need to backtrack
class Solution {
public:
bool dfs(vector<vector<char>>& matrix, string &str, int x, int y, int u) {
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
if (matrix[x][y] == str[u]) {
if (u == str.size() - 1) return true;
char t = matrix[x][y];
matrix[x][y] = '#';
for (int i = 0; i < 4; i ++) {
int f = x + dx[i], s = y + dy[i];
if (f >= 0 && s >= 0 && f < matrix.size() && s < matrix[0].size())
// 如果为真,则直接返回
if (dfs(matrix, str, f, s, u + 1))
return true;
}
matrix[x][y] = t;
}
return false;
}
bool hasPath(vector<vector<char>>& matrix, string &str) {
for (int i = 0; i < matrix.size(); i ++)
for (int j = 0; j < matrix[0].size(); j ++)
if (dfs(matrix, str, i, j, 0))
return true;
return false;
}
};