题解 | #机器人的运动范围#

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

欢迎关注我的博客:https://www.cnblogs.com/Cloud-king/

#include <cstring>
#include <unistd.h>
class Solution {
public:
    int swsum(int x){
        int ans=0;
        while (x>=1) {
            ans+=x%10;
            x/=10;
        }
        return ans;
    }
    int vis[105][105]={0};
    int nex[4][2]={{-1,0},{0,-1},{1,0},{0,1}};
    int ans=1;
    void dfs(int th,int x,int y,int n,int m){
        for(int i=0;i<4;i++){
            int dx=x+nex[i][0];
            int dy=y+nex[i][1];
            int tmp=swsum(dx)+swsum(dy);  
            //cout << dx << " " << dy << endl;  
            if(dx<n&&dx>=0&&dy>=0&&dy<m&&tmp<=th&&vis[dx][dy]==0){     
                vis[dx][dy]=1;
                ans++;               
                //cout << dx << " " << dy << " " << ans << endl;
                dfs(th,dx,dy,n,m);
                //vis[dx][dy]=0;  //重复的格子也能走;
            }
        }
    }
    int movingCount(int threshold, int rows, int cols) {
        memset(vis, 0, sizeof(vis));
        vis[0][0]=1;
        dfs(threshold,0,0,rows,cols);
        return ans;
    }
};

不需要回溯,只需要一个变量记录那些搜索过程中遇到的能到的格子,因为题目只是记录能到达的格子数量而不是一条可行的不能回头的路径。感觉更适合bfs去做。

#include <cstring>
#include <queue>
#include <unistd.h>
#include <utility>
class Solution {
public:
    int swsum(int x){
        int ans=0;
        while (x>=1) {
            ans+=x%10;
            x/=10;
        }
        return ans;
    }
    int vis[105][105]={0};
    int nex[4][2]={{-1,0},{0,-1},{1,0},{0,1}};
    int ans=0;
    void bfs(int th,int n,int m){
        queue<pair<int,int>> q;
        q.push({0,0});
        while (!q.empty()) {
            pair<int, int> tmp=q.front();
            q.pop();    //不要忘记pop
            ans++;
            for(int i=0;i<4;i++){
                int dx=tmp.first+nex[i][0];
                int dy=tmp.second+nex[i][1];
                int su=swsum(dx)+swsum(dy);
                if(dx>=0&&dx<n&&dy>=0&&dy<m&&su<=th&&vis[dx][dy]==0){
                    q.push({dx,dy});
                    vis[dx][dy]=1;
                }
            }
        }
    }
    int movingCount(int threshold, int rows, int cols) {
        memset(vis, 0, sizeof(vis));
        vis[0][0]=1;
        bfs(threshold, rows, cols);
        return ans;
    }
};
全部评论

相关推荐

渐好:软光栅真的写明白了吗,既然是软渲那技术栈不应该使用OpenGL,光追和bvh既不算什么高级渲染技术更不应该属于软渲的内容,git那个项目没啥用,建议把前两个项目重新组织一下语言,比如软渲染那个项目 冯着色和msaa、贴图这几项分开写,写的到位点,如果你还学过光追那就单独写出来,如果没把握考官问你答不上来就别写给自己找麻烦,在技术栈那一栏简单提一下自己学过就行,这样杂的放在一起不太严谨,个人愚见.
点赞 评论 收藏
分享
Cherrycola01:0实习 0项目 约等于啥也没有啊 哥们儿这简历认真的吗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务