classSolution { // 返回 x 的位数之和 intget(int x){ int sum = 0; for (; x; x /= 10) sum += x % 10; return sum; } public: intmovingCount(int m, int n, int k){ vector<vector<bool>> visit(m, vector<bool>(n, false)); visit[0][0] = true; queue<pair<int, int>> q; q.emplace(0, 0); int dir[2][2] = {{1, 0}, {0, 1}}; // dir[0] 向右,dir[1] 向下 int ans = 1; // (0, 0) 点 while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 2; ++i) { int nx = x + dir[i][0], ny = y + dir[i][1]; // 下一个坐标点 // 省略了 nx < 0 || ny < 0 if (nx >= m || ny >= n || visit[nx][ny] || get(nx) + get(ny) > k) continue; visit[nx][ny] = true; // (nx, ny) 可达 q.emplace(nx, ny); ans++; } } return ans; } };
classSolution { // 返回 x 的位数之和 intget(int x){ int sum = 0; for (; x; x /= 10) sum += x % 10; return sum; } // 返回从 (i, j) 点出发可以到达多少格子 intdfs(vector<vector<bool>>& visit, int m, int n, int i, int j, int k){ // 省略了 i < 0 || j < 0 if (i >= m || j >= n || visit[i][j] || get(i) + get(j) > k) return0; visit[i][j] = true; return1 + dfs(visit, m, n, i + 1, j, k) + dfs(visit, m, n, i, j + 1, k); } public: intmovingCount(int m, int n, int k){ vector<vector<bool>> visit(m, vector<bool>(n, false)); returndfs(visit, m, n, 0, 0, k); } };