js 求解释注意除法取整,这里直接使用字符串处理
/**
* @param {number} threshold
* @param {number} rows
* @param {number} cols
* @return {number}
*/
var movingCount = function(k, rows, cols) {
const dx = [-1, 0, 1, 0], dy = [0, 1, 0, -1];
const vt = new Array(rows).fill(0).map(() => new Array(cols).fill(false));
const dfs = (r, c) => {
const t = (''+r+c).split('').reduce((sum, cur) => sum += +cur, 0);
if (r < 0 || r >= rows || c < 0 || c >= cols || vt[r][c] || t > k) {
return 0;
}
vt[r][c] = true;
let ans = 1;
for (let d = 0; d < 4; ++d) {
let x = dx[d] + r, y = dy[d] + c;
ans += dfs(x, y);
}
return ans;
}
return dfs(0, 0);
};