intgetTwoSum(int x, int y){ return getSum(x) + getSum(y); }
intgetSum(int x){ int sum = 0; for (; x; x /= 10) { sum += x % 10; } return sum; }
constint dr[4] = {-1, 0, 1, 0}, dc[4] = {0, 1, 0, -1}; int64_t res = 0; int g_m, g_n, g_k; vector<vector<bool>> st; intmovingCount(int m, int n, int k){ g_m = m, g_n = n, g_k = k; st = vector<vector<bool>>(m, vector<bool>(n, false)); dfs(0, 0); return res; }
voiddfs(int r, int c){ res++; st[r][c] = true; for (int d = 0; d < 4; d++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < g_m && nec >= 0 && nec < g_n && getTwoSum(ner, nec) <= g_k && !st[ner][nec]) { dfs(ner, nec); } } } };
privateintgetSum(int x){ int sum = 0; for (; x > 0; x /= 10) { sum += x % 10; } return sum; }
privateintgetTwoSum(int x, int y){ return getSum(x) + getSum(y); }
int g_m, g_n, g_k; int[] dr, dc; boolean[][] st; int res = 0; publicintmovingCount(int m, int n, int k){ g_m = m; g_n = n; g_k = k; dr = newint[] {-1, 0, 1, 0}; dc = newint[] {0, 1, 0, -1}; st = newboolean[m][n]; for (int i = 0; i < m; i++ ) { Arrays.fill(st[i], false); }
dfs(0, 0);
return res; }
privatevoiddfs(int r, int c){ res++; st[r][c] = true; for (int d = 0; d < 4; d++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < g_m && nec >= 0 && nec < g_n && !st[ner][nec] && getTwoSum(ner, nec) <= g_k) { dfs(ner, nec); } } } }
// 执行用时: 4 ms // 内存消耗: 6.4 MB classSolution { public: intgetSum(int x){ int sum = 0; for (; x; x /= 10) { sum += x % 10; } return sum; }
intgetTwoSum(int x, int y){ return getSum(x) + getSum(y); }
int g_m, g_n, g_k; vector<vector<bool>> st; constint dr[4] = {0, 1}, dc[4] = {1, 0}; int res = 0; intmovingCount(int m, int n, int k){ g_m = m, g_n = n, g_k = k; st = vector<vector<bool>>(m, vector<bool>(n, false));
for (; q.size();) { int r = q.front().first, c = q.front().second; q.pop(); res++; for (int d = 0; d < 2; d++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < g_m && nec >= 0 && nec < g_n && !st[ner][nec] && getTwoSum(ner, nec) <= g_k) { q.push({ner, nec}); st[ner][nec] = true; // 避免相邻节点竞争 } } } } };
// 执行用时: 5 ms // 内存消耗: 35.8 MB classSolution{ intgetSum(int x){ int sum = 0; for (; x > 0; x /= 10) { sum += x % 10; } return sum; }
intgetTwoSum(int x, int y){ return getSum(x) + getSum(y); }
int m, n, k; int[] dr, dc; boolean[][] st; int res = 0; publicintmovingCount(int m, int n, int k){ this.m = m; this.n = n; this.k = k; dr = newint[] {0, 1}; dc = newint[] {1, 0}; st = newboolean[m][n]; for (int i = 0; i < m; i ++) { Arrays.fill(st[i], false); }
for (; q.size() > 0;) { int _hash = q.remove(); int r = _hash / n, c = _hash % n; res++;
for (int i = 0; i < 2; i++) { int ner = r + dr[i], nec = c + dc[i]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && !st[ner][nec] && getTwoSum(ner, nec) <= k) { q.add(ner * n + nec); st[ner][nec] = true; } } } } }