第一题:矩阵中的路径
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型vector<vector<>>
* @param word string字符串
* @return bool布尔型
*/
bool hasPath(vector<vector<char> >& matrix, string word) {
for(int i=0; i<matrix.size();i++){
for(int j=0; j<matrix[i].size();j++){
if(dfs(matrix, word, 0, i, j))
return true;
}
}
return false;
}
bool dfs(vector<vector<char>> &matrix, string &word, int u, int x, int y){
//回溯停止条件
if(word.size()==1 && matrix[0][0] == word[0]) return true; //判断字符串长度为1的情况
if(u==word.size()) return true;
if(word[u] != matrix[x][y]) return false;
//单层处理方法
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
char t = matrix[x][y];
matrix[x][y] = '*';
for(int i=0; i<4; i++){
int a = x + dx[i], b = y + dy[i];
if(a>=0 && a<matrix.size() && b >=0 && b<matrix[a].size()){
if(dfs(matrix, word, u+1, a, b)) return true;
}
}
//回溯
matrix[x][y] = t;
return false;
}
};
第二题:机器人的运动范围
class Solution {
public:
int get_single_sum(int x){
int s = 0;
while(x) s += x % 10, x /= 10;
return s;
}
//当前位置的位数和
int get_sum(pair<int, int> p){
return get_single_sum(p.first) + get_single_sum(p.second);
}
int movingCount(int threshold, int rows, int cols) {
int res = 0; //计数
if(!rows || !cols) return 0;
vector<vector<bool>> st(rows, vector<bool>(cols, false));
queue<pair<int, int>> q;
q.push({0,0});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while(q.size()){
auto t = q.front();
q.pop();
//跳出下一个循环
if(get_sum(t) > threshold || st[t.first][t.second]) continue;
res++;
st[t.first][t.second] = true;
for(int i=0; i<4; i++){
int x = t.first + dx[i], y = t.second + dy[i];
if(x < rows && x>=0 && y<cols && y>=0){
q.push({x ,y});
}
}
}
return res;
}
};