SOURCE

let grid =  [
  ["1","1","0","0","0"],
  ["1","1","0","1","0"],
  ["0","0","1","1","0"],
  ["0","1","1","1","1"],
  ["1","0","0","0","0"],
]

let walk = 0
function setNum( i, j) {
    grid[i][j] = '2'
    walk ++
    if (i + 1 < grid.length && grid[i + 1][j] === '1')  {
        setNum(i + 1, j)
    }
    if (j + 1 <  grid[0].length && grid[i][j + 1] === '1')  {
        setNum(i , j + 1)
    }
    if (i - 1 > 0 && grid[i - 1][j] === '1')  {
        setNum(i - 1, j)
    }
    if (j - 1 > 0 && grid[i][j - 1] === '1')  {
        setNum(i , j - 1)
    }
}
let count = 0
for(let i = 0; i < grid.length; i++) {
    for(let j = 0; j < grid[0].length; j++) {
        if (grid[i][j] === '1') {
            setNum(i, j)
            count ++
        }
        walk ++
    }
}
console.log(walk)
console.log(count)
console 命令行工具 X clear

                    
>
console