剑指offer:机器人运动范围
机器人的运动范围
http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8
1.数字之和的阈值相当于将矩阵中的某些点标成了陷阱,说明其不能走;
2.用宽搜扩展一遍,定义一个int res=0;扩展一个,答案加1,复杂度为格子的个数
3.定义队列,将其坐标放进去
queue<pair<int,int>> q;
q.push({0,0});
4.定义二维的状态变量,并初始化
vector<vector<bool>> st(rows, vector<bool>(cols, false));
5.宽搜模板
q.push(第一个元素)
//将距离变为0;初始状态
while(q.size()){
auto t=q.front() //将队头元素取出
q.pop() //弹出队头元素
//扩展,矩阵的话就是4个方向,定义dx[] dy[];
//循环4个方向。如果在边界内,且没走过,加到答案里;
具体代码如下</bool></bool>
class Solution {
public:
int get_sum(pair<int, int> p) {
int s = 0;
while (p.first) {
s += p.first % 10;
p.first /= 10;
}
while (p.second) {
s += p.second % 10;
p.second /= 10;
}
return s;
}
int movingCount(int threshold, int rows, int cols)
{
if (!rows || !cols) return 0;
queue<pair<int,int>> q;
vector<vector<bool>> st(rows, vector<bool>(cols, false));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int res = 0;
q.push({0, 0});
while (q.size()) {
auto t = q.front();
q.pop();
if (st[t.first][t.second] || get_sum(t) > threshold) 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 >= 0 && x < rows && y >= 0 && y < cols) q.push({x, y});
}
}
return res;
}
};



查看22道真题和解析