题解 | #数字在升序数组中出现的次数#
矩阵中的路径
http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型vector<vector<>>
* @param word string字符串
* @return bool布尔型
*/
// write code here
bool search(vector<vector<char> >& matrix, int r, int c, string word, int cnt=0){
if(r<0 || r >= matrix.size() || c < 0 || c >= matrix[0].size() || matrix[r][c] != word[cnt]) return false;
if(cnt >= word.size()-1) return true;
char temp = matrix[r][c];
matrix[r][c] = '.';
bool result = search(matrix, r + 1, c, word, cnt+1) || search(matrix, r - 1, c, word, cnt+1) || search(matrix, r, c + 1, word, cnt+1) || search(matrix, r, c - 1, word, cnt+1);
matrix[r][c] = temp;
return result;
}
bool hasPath(vector<vector<char> >& matrix, string word) {
// write code here
int n = matrix.size();
int m = matrix[0].size();
for(int r=0; r<n; r++){
for(int c=0; c<m; c++){
if(search(matrix, r, c, word, 0)){
return true;
}
}
}
return false;
}
};
把是否能走的 flag 直接存在原数组中,可以避免建立 mxn 的标记数组。