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

    剑指OFFER 机器人的运动范围

    矩形搜索的变形,可以深搜,也可以广搜. 思维上没有什么难度,但是需要细心.

    深搜代码

    class Solution {
    public:
        
        int counter = 0;
        vector<pair<int,int> > rotate_fac;
        int m_threshold;
        int m_rows;
        int m_cols;
        vector<vector<bool> > matrix;
    
        bool check(int x,int y)
        {
            int sum = 0;
            int xx = x;
            int yy = y;
            while (xx != 0) {
                sum += xx % 10;
                xx /= 10;
            }
            while (yy != 0) {
                sum += yy % 10;
                yy /= 10;
            }
            if(x>=0 && y>=0 && x<m_rows && y<m_cols && matrix[x][y]==false && sum <= m_threshold)return true;
            else return false;
        }
        
        void recur(int x,int y)
        {
            matrix[x][y]=true;
            counter++;
            for(int i=0;i<4;i++)
            {
                if(check(x+rotate_fac[i].first,y+rotate_fac[i].second))
                {
                    recur(x+rotate_fac[i].first,y+rotate_fac[i].second);
                }
            }
        }
    
        int movingCount(int threshold, int rows, int cols)
        {
            //handling special cases
            if (rows == 0 || cols == 0 || threshold < 0)return 0;
    
            //initialize
            counter = 0;
            m_threshold =  threshold;
            m_rows = rows;
            m_cols = cols;
            rotate_fac.push_back(pair<int,int>(0,1));
            rotate_fac.push_back(pair<int,int>(1,0));
            rotate_fac.push_back(pair<int,int>(0,-1));
            rotate_fac.push_back(pair<int,int>(-1,0));
            matrix.resize(rows);
            for(int i=0;i<rows;i++)
            {
                matrix[i].resize(cols);
            }
            
            recur(0,0);
            
            return counter;
        }
    };
    
  • 相关阅读:
    noexcept(c++11)
    右值引用和std::move函数(c++11)
    mint-ui 取值
    apicloud 注意事项
    倒计时
    获取第n天日期
    防止split没有切割的变量报错
    return
    时间戳转为日期
    echarts 中 请求后台改变数据
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12262479.html
Copyright © 2011-2022 走看看