zoukankan      html  css  js  c++  java
  • 剑指offer-机器人的运动范围

    剑指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; 
        }
    };
    
  • 相关阅读:
    Android的startActivityForResult()与onActivityResult()与setResult()参数分析,activity带参数的返回
    git stash 保存当前工作状态
    vim diff 的使用
    git pull 命令
    java 开发环境安装
    vim 处理换行符
    git 操作分支
    git 操作远程仓库地址
    vim 宏的使用
    Chrome 调试技巧
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/6607319.html
Copyright © 2011-2022 走看看