首页 > 其他 > 详细

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

时间:2020-08-03 23:10:17      阅读:66      评论:0      收藏:0      [点我收藏+]

思路:

宽度优先搜索

确定起点坐标后,向四周进行搜索

在节点扩展时需要判断是否重复,是否出边界,横纵坐标数字之和小于K

 

代码:

class Solution {
public:
    //坐标进行计算
    int single_sum(int x)
    {
        int s=0;
        while(x) s+=x%10,x/=10;
        return s;
    }
    int get_sum(pair<int,int>p)
    {
        return single_sum(p.first) + single_sum(p.second);
    }
    int movingCount(int threshold, int rows, int cols)
    {
        int res=0;
        //判断为空条件
        if(!rows || !cols) return 0;
        
        //判断矩阵中搜索重复问题
        vector<vector<bool>> st(rows,vector<bool>(cols));
        //将矩阵的坐标看成是一个点放入队列中
        queue<pair<int,int>> q;
        
        q.push({0,0});
        
        int dx[4]={-1,0,1,0}, dy[4]={0,-1,0,1};
        while(q.size())
        {
            auto t=q.front();
            q.pop();
            
            //判断边界条件
            if(get_sum(t)> threshold ||st[t.first][t.second]) continue;
            res ++;
            //对走过的点进行标记
            st[t.first][t.second] = true;
            
            //机器人移动
            for(int i=0;i<4;i++)
            {
                int x=t.first + dx[i], y=t.second+dy[i];
                //判断
                if(x>=0 && x<rows && y>=0 && y<cols) q.push({x,y})
            }
        }
        return res;
    }
};

 

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

原文:https://www.cnblogs.com/Sunshineboy1/p/13428177.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!