• 剑指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;
        }
    };
    
  • 相关阅读:
    一个简单的MVVM雏形
    sass学习笔记1
    col标签的相关实验
    背景半透明rgba最佳实践
    angular性能优化心得
    环视非捕获分组
    5月23日Google就宣布了Chrome 36 beta
    浏览器 user-agent 字符串的故事
    迷你MVVM框架 avalonjs 沉思录 第3节 动态模板
    迷你MVVM框架 avalonjs 1.3.1发布
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12262479.html
Copyright © 2020-2023  润新知