1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
class Solution { public: int movingCount(int threshold, int rows, int cols) { if (rows < 0 || cols < 0) return 0;
vector<vector<bool>> visited(rows, vector<bool>(cols, false)); return movingCountCore(threshold, rows, cols, visited, 0, 0); }
int movingCountCore(int threshold, int rows, int cols, vector<vector<bool>> &visited, int i, int j) { if (i < 0 || i >= rows || j < 0 || j >= cols || !canReach(threshold, i, j) || visited[i][j] == true) return 0; visited[i][j] = true; return movingCountCore(threshold, rows, cols, visited, i - 1, j) + movingCountCore(threshold, rows, cols, visited, i, j + 1) + movingCountCore(threshold, rows, cols, visited, i + 1, j) + movingCountCore(threshold, rows, cols, visited, i, j - 1) + 1; }
bool canReach(int threshold, int x, int y) { int sum = 0; while (x > 0) { sum += x % 10; x /= 10; } while (y > 0) { sum += y % 10; y /= 10; } return sum <= threshold; } };
class Solution { public: int movingCount(int threshold, int rows, int cols) { if (rows < 0 || cols < 0) return 0;
vector<vector<bool>> visited(rows, vector<bool>(cols, false)); queue<pair<int, int>> q; q.push(make_pair(0, 0)); visited[0][0] = true;
int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, 1, 0, -1 }; int cnt = 0; while (!q.empty()) { cnt ++; int x = q.front().first, y = q.front().second; q.pop(); for (int i = 0; i < 4; i ++) { int a = x + dx[i], b = y + dy[i]; if (a >= 0 && a < rows && b >= 0 && b < cols && !visited[a][b] && canReach(threshold, a, b)) { q.push(make_pair(a, b)); visited[a][b] = true; } } } return cnt; }
bool canReach(int threshold, int x, int y) { int sum = 0; while (x > 0) { sum += x % 10; x /= 10; } while (y > 0) { sum += y % 10; y /= 10; } return sum <= threshold; } };
|