标签:first amp esc span public sub -- style bool
剑指offer--机器人的运动范围
题解:
使用BFS,从[0, 0] 开始bfs。
class Solution {
public:
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {1, -1, 0, 0};
bool check(int x, int y, int th){
int cnt = 0;
while(x){
cnt += x%10;
x = x/10;
}
while(y){
cnt += y%10;
y = y/10;
}
return cnt <= th;
}
int movingCount(int threshold, int rows, int cols)
{
vector<vector<int> > vis(rows, vector<int>(cols, 0));
queue<pair<int, int>> sq;
sq.push(make_pair(0, 0));
vis[0][0] = 1;
int cur_x, cur_y, tmp_x, tmp_y, ans=0;
if(threshold >= 0){
ans = 1;
}
while(!sq.empty()){
cur_x = sq.front().first; cur_y = sq.front().second;
sq.pop();
for(int i=0; i<4; ++i){
tmp_x = cur_x + dx[i]; tmp_y = cur_y + dy[i];
if( tmp_x>=0 && tmp_x<rows && tmp_y>=0 && tmp_y<cols && vis[tmp_x][tmp_y]==0 && check(tmp_x, tmp_y, threshold) ){
ans++; vis[tmp_x][tmp_y] = 1;
sq.push(make_pair(tmp_x, tmp_y));
}
}
}
return ans;
}
};
标签:first amp esc span public sub -- style bool
原文地址:http://www.cnblogs.com/zhang-yd/p/6607319.html