# 59. 小华地图寻宝

59

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
rl.on('line', function(line) {
    const [m, n, k] = input.split(' ').map(Number);
    const visited = Array.from({length: m}, () => Array(n).fill(false));
    console.log(dfs(0, 0, m, n, k, visited));
});

function dfs(x, y, m, n, k, visited) {
    // x,y是否越界,或者已被访问多, 或者数位和大于k
    if (x < 0 || y < 0 || x >=m || y>=n || visited[x][y] || sum(x) + sum(y) > k) {
        return 0;
    }
    visited[x][y] = true;
    return 1 + dfs(x+1, y, m, n, k, visited) + dfs(x-1, y, m, n, k, visited) + dfs(x, y+1, m, n, k, visited) + dfs(x, y-1, m, n, k, visited)}

function sum(num) {
    let res = 0;
    while(num > 0) {
        res += num % 10;
        num = Math.floor(num / 10);
    }
    return res;
}
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