반응형
const dx = [-1, 0, 1, 0]
const dy = [0, -1, 0, 1]
const dfs = (maps, visited, x, y, sum) => {
visited[x][y] = 1
for (let i = 0; i < 4; i++) {
const [nx, ny] = [x + dx[i], y + dy[i]]
if (0 <= nx && nx < maps.length &&
0 <= ny && ny < maps[0].length &&
maps[nx][ny] !== 'X' && !visited[nx][ny]) {
sum += dfs(maps, visited, nx, ny, +maps[nx][ny])
}
}
return sum
}
const solution = (maps) => {
const res = []
const [x, y] = [maps.length, maps[0].length]
const visited = Array.from({ length: x }, () => Array(y).fill(0))
for (let i = 0; i < x; i++) {
for (let j = 0; j < y; j++) {
if (maps[i][j] !== 'X' && !visited[i][j]) {
res.push(dfs(maps, visited, i, j, +maps[i][j]))
}
visited[i][j] = 1
}
}
return res.length ? res.sort((a, b) => a - b) : [-1]
}
dfs