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;
        }
    };
    
  • 相关阅读:
    nginx:配置详细说明
    linux:/etc/rc.local 不能自动启动问题
    nginx:403 forbidden 二种原因
    nginx:虚拟主机配置
    linux:lnmp环境搭建
    php:mysqli扩展
    linux:磁盘的分割、检验、格式化与挂载
    webpack
    js的window.onscroll事件兼容各大浏览器
    js window事件解析(转载)
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12262479.html
Copyright © 2011-2022 走看看