码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer-机器人的运动范围

时间:2017-03-23 21:19:51      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:first   amp   esc   span   public   sub   --   style   bool   

剑指offer--机器人的运动范围

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

 

题解:

  使用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; 
    }
};

 

剑指offer-机器人的运动范围

标签:first   amp   esc   span   public   sub   --   style   bool   

原文地址:http://www.cnblogs.com/zhang-yd/p/6607319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!