剑指offer | 机器人的运动范围(BFS C++)

题目描述

剑指offer 原题链接

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

Algorithm

(Breadth First Search) O ( n m ) O(n*m)

(1)This is a typical BFS problem. We can first let illegal blocks be visited.(Actually we can do this step in BFS, by judging whether the block is legal)
(2) Second, we do a BFS for four directions, use a stack to do this problem
(3)Finally, traverse all the legal blocks, and add them to the answer

The time complexity is O ( n m ) O(n*m) ,and the space complexity is O ( n m ) O(n * m) : need q [ n m ] q[n*m] to store information

C++

class Solution {
public:
    typedef pair<int, int> PII;
    int st[200][200];
    int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
    PII q[200 * 200];
    int hh = 0, tt = 0;
       
    int dfs(int i, int j, int rows, int cols) {
        q[tt ++] = {i, j};
        st[i][j] = true;
        
        int res = 0;
        while(hh < tt) {
            auto t = q[tt - 1];
            tt --;         
            res ++;
            
            for (int d = 0; d < 4; d ++) {
                int a = dx[d] + t.first, b = dy[d] + t.second;
                if (a < 0 || a >= rows || b < 0 || b >= cols) continue;
                if (st[a][b] == true) continue;            
                st[a][b] = true;
                q[tt ++] = {a, b};           
            }          
        }
        
        return res;
    }
    
    int digitSum(int n) {
        int t = 0;
        while(n) {
            t += n % 10;
            n /= 10;
        }
        return t;
    }
    
    int movingCount(int threshold, int rows, int cols)
    {
        if (!rows && !cols) return 0;
        if (threshold < 0) return 0;
        memset(st, false, sizeof st); // Don't forget to initialize the array st in Nowcoder
        
        // First let illegal blocks be visited
        for (int i = 0; i < rows; i ++) {
            for (int j = 0; j < cols; j ++) {
                if (digitSum(i) + digitSum(j) > threshold) st[i][j] = true;
            }
        }
        
        // Second we do a breadth first search
        return dfs(0, 0, rows, cols);
    }
};

写在最后:我的博客主要是对计算机领域所学知识的总结、回顾和思考,把每篇博客写得通俗易懂是我的目标,分享技术和知识是一种快乐 ,非常欢迎大家和我一起交流学习,有任何问题都可以在评论区留言,也期待与您的深入交流(^∀^●)

发布了270 篇原创文章 · 获赞 111 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104498134
今日推荐