[剑指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也可以的
点赞
送花
回复
分享
发布于 2019-10-18 16:27

相关推荐

头像
不愿透露姓名的神秘牛友
05-14 18:44
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务