题解 | #矩阵中的路径#
矩阵中的路径
https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
class Solution {
private:
bool hasNext(int x, int y, int pathLen, string word,
vector<vector<char> >& matrix) {
/*
@brief: 在指定位置的元素周围相邻位置找下一个节点
@param:
dir: 来的方向 1 从左往右 2 从上往下 3 从右往左 4 从下往上
wordLen: 当前的长度
*/
if (pathLen == word.size()) {
return true;
}
if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() ||
matrix[x][y] != word[pathLen]) {
return false;
}
pathLen++;
char temp = matrix[x][y]; // 回溯
matrix[x][y] = '#'; //不为26个字母的都可以,用于标记已走过的路径
bool found = hasNext(x + 1, y, pathLen, word, matrix) ||
hasNext(x - 1, y, pathLen, word, matrix) ||
hasNext(x, y + 1, pathLen, word, matrix) ||
hasNext(x, y - 1, pathLen, word, matrix);
matrix[x][y] = temp; // 回溯
return found;
}
public:
bool hasPath(vector<vector<char> >& matrix, string word) {
int col = matrix[0].size();
int row = matrix.size();
// 为空的判断
if (matrix.empty() || word.empty()) {
return false;
}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
if (matrix[j][i] == word[0]) {
if (hasNext(j, i, 0, word, matrix)) return true;
}
}
}
return false;
}
};
腾讯音乐娱乐集团公司福利 285人发布
