반응형
function solution(maps) {
const xLen = maps.length
const yLen = maps[0].length
const vistedMap = Array.from(Array(xLen),()=>Array(yLen).fill(false))
const offset = [
[-1,0], //좌
[1,0], //우
[0,-1], //상
[0,1], //하
]
const answer = []
function sumCountArea(x,y){
const stack = [[x,y]]
let count = maps[x][y]*1
while(stack.length > 0){
const [xP,yP] = stack.pop()
offset.forEach(([moveX,moveY])=>{
const nX = xP + moveX
const nY = yP + moveY
if(nX >= 0 && nX < xLen && nY >= 0 && nY < yLen && !vistedMap[nX][nY] && maps[nX][nY] != "X"){
vistedMap[nX][nY] = true
count += maps[nX][nY]*1
stack.push([nX,nY])
}
})
}
answer.push(count)
}
for(let i = 0; i < xLen; i++){
for(let j = 0; j < yLen; j++){
if(vistedMap[i][j] || maps[i][j] == "X"){
continue
}
vistedMap[i][j] = true
sumCountArea(i,j)
}
}
console.log(answer)
answer.sort((a,b)=>a-b)
return answer.length > 0 ? answer: [-1]
}
총합, 최단거리
대부분 비슷하다.
2차배열이 주어질때
2차배열을 만들어서 방문여부를 체크하고
stack이나 que로 총합을 구하는게 비슷함
중요한건 루프문을 각자 짜는것
반응형
'개발관련 > 매일 코딩 테스트 챌린지' 카테고리의 다른 글
자바스크립트 코딩 테스트 구름 문제 연속 점수 문제 (0) | 2023.07.06 |
---|---|
[자바스크립트] 코딩테스트 큰 팩토리얼 (0) | 2023.07.06 |
[코딩테스트 준비]자바스크립트 그리드 알고리즘 코딜리티 연습 javascript algorithm codility greedy (1) | 2023.04.13 |
[프로그래머스] 제일 작은 수 제거하기 (JavaScript) (0) | 2020.10.02 |
[프로그래머스] 행렬의 덧셈 (JavaScript) (0) | 2020.09.21 |