剑指Offer——JZ66.机器人的运动范围【BFS | DFS】

题目传送门


在这里插入图片描述
样例:5,10,10
输出:21


题解

  • 直接BFS或者DFS即可。
  • 注意:memset不能对动态创建的二维数组初始化,因为每次 new 或者 malloc 的时候,分配的不是连续地址,每行的元素地址连续,各行之间地址不保证连续。
  • 同样可以使用一维数组表示二维数组
    bool *vis;
    vis = new bool[sizeof(bool) * rows * cols];
    memset(vis, false, sizeof(bool) * rows * cols);
    vis[i * cols + j];	// i行j列的元素
    

AC-Code

class Solution {
private:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    bool **vis;
public:
    int movingCount(int threshold, int rows, int cols) {
        if(threshold <= 0)    return 0;
        vis = new bool*[rows];
        for(int i = 0; i < rows; ++i) {
            vis[i] = new bool[cols];
            memset(vis[i], false, sizeof(bool) * cols);
        }
        int ans = 1;
        queue<pair<int,int>> que;
        que.push(make_pair<int,int>(0,0));
        vis[0][0] = true;
        while(!que.empty()) {
            int x = que.front().first;
            int y = que.front().second;
            que.pop();
            for(int i = 0; i < 4; ++i) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if(judge(nx, ny, threshold, rows, cols)) {
                    que.push(pair<int,int>(nx, ny));
                    vis[nx][ny] = true;
                    ++ans;
                }
            }
        }
        delete[] vis;
        return ans;
    }
    bool judge(int x, int y, int k, int rows, int cols) {
		if (x < 0 || x >= rows || y < 0 || y >= cols)    return false;
		int num = 0, nx = x, ny = y;
		while (x > 0) {
			num += x % 10;
			x /= 10;
		}
		while (y > 0) {
			num += y % 10;
			y /= 10;
		}
		return !vis[nx][ny] && num <= k;
	}
    
};

猜你喜欢

转载自blog.csdn.net/Q_1849805767/article/details/106544220