프로그래머스 LEVEL 2(프렌즈4블록)
-
사용 언어 : javascript
-
해결 날짜 : 2022-10-16
- 해결 방법 :
- 각 반복마다 board를 돌며 4블록인지 체크 후 정사각형이면 pop 배열에 push()
- pop 배열에 값이 있다면 하나씩 꺼내어 4블록 부분 board에서 공백(‘ ‘)값으로 변경
- 위 아래 사이에 공백이 존재할 때 아래로 끌어 내림
- board를 돌 때 4블록이 존재하지 않는 경우 break
- board에 포함된 공백(‘ ‘) 값 return
- 회고 :
- 4블록 제거 후 아래로 끌어 내리는 작업을 생각하는데에 시간이 소요됨
-
코드
function solution(m, n, board) { board = board.map((row) => row.split('')); const move = [[1, 0], [0, 1], [1, 1]]; const pop = []; const isSquare = (x, y) => { if (board[x][y] === ' ') return false; for (let i = 0; i < move.length; i++) { if (board[x][y] !== board[x + move[i][0]][y + move[i][1]]) return false; } return true; } const removeSquare = (x, y) => { board[x][y] = ' '; for (let i = 0; i < move.length; i++) { board[x + move[i][0]][y + move[i][1]] = ' '; } } const pullToBottom = () => { for (let j = 0; j < n; j++) { const rest_column = Array.from({ length: m }, (_, i) => board[i][j]).filter(e => e !== ' '); const result_column = [...Array.from({ length: m - rest_column.length }, () => ' '), ...rest_column]; result_column.forEach((e, i) => { board[i][j] = e; }); } }; while (true) { for (let i = 0; i < m - 1; i++) { for (let j = 0; j < n - 1; j++) { if (isSquare(i, j)) { pop.push([i, j]) } } } if (!pop.length) break; while (pop.length) { removeSquare(...pop.pop()); } pullToBottom(); } return board.flat().filter((e) => e === ' ').length; }
- 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges