[剑指offer 编程题]机器人的运动范围
机器人的运动范围
http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
//生成一个矩阵,里面所有的值置为0为没走过,-1为走不了,1为走了的;
vector<vector<int>> m_map;
for(int i = 0;i<rows;i++){
vector<int> col_map;
for(int j = 0;j<cols;j++){
if(if_block(i,j,threshold)){
col_map.push_back(-1);
//cout << "X ";
}
else {
col_map.push_back(0);
//cout << "O ";
}
}
//cout << endl;
m_map.push_back(col_map);
}//map构建
return reverseMap(0,0,0,m_map,rows,cols);
}
int reverseMap(int i,int j,int num_step,vector<vector<int>>& m_map,int rows,int cols){
//修改值
if(m_map.at(i).at(j)!=-1){
m_map.at(i).at(j) = -1;
num_step++;
}
if( i+1 < rows && m_map.at(i+1).at(j) != -1){
num_step = reverseMap(i+1,j,num_step,m_map,rows,cols);
}
if( i-1 >= 0 && m_map.at(i-1).at(j) != -1){
num_step = reverseMap(i-1,j,num_step,m_map,rows,cols);
}
if( j-1 >= 0 && m_map.at(i).at(j-1) != -1){
num_step = reverseMap(i,j-1,num_step,m_map,rows,cols);
}
if( j+1 < cols && m_map.at(i).at(j+1) != -1){
num_step = reverseMap(i,j+1,num_step,m_map,rows,cols);
}
return num_step;
}
bool if_block(int i,int j,int threshold){
if(bit_sum(i)+bit_sum(j) <= threshold)return false;
return true;
}
int bit_sum(int n){
int sum = 0;
while(n!=0){
int bi = n%10;
sum += bi;
n = (n - bi)/10;
}
return sum;
}
};
九号公司成长空间 1人发布
查看11道真题和解析