공부블로그
[프로그래머스] 크레인 인형뽑기 본문
https://programmers.co.kr/learn/courses/30/lessons/64061
코딩테스트 연습 - 크레인 인형뽑기 게임
[[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] [1,5,3,5,1,2,1,4] 4
programmers.co.kr
코드 설명
- 인형이 어느 위치(인덱스)까지 찼는지를 for문을 통해 검사한 후 top[ ]에 저장.
- board[ ][ ]는 이차원 배열이라서 위 사진에서 가로가 배열의 최상위 레벨을 의미하고, 세로가 그 이하레벨을 의미한다.
따라서 moves에서 1이라고 했을때 board[ 3 ] [ 1-1 ]위치에서 크레인함.
- for each문: top[ ]의 값이 board.length라면 move위치의 board가 비워져 있다는 의미. 따라서 continue
빈 stack에서 peek()를 하면 Exception. 먼저 비어있는지 확인하고
그렇지 않으면 바구니의 인형과 동일한지 확인 후에 push한다.
import java.util.*;
class Solution {
public int solution(int[][] board, int[] moves) {
System.out.println(Arrays.deepToString(board));
Stack<Integer> stack = new Stack<Integer>(); //바구니
int count = 0; //터트려진 횟수
// board의 top 인덱스 저장 (board[*][] *위치)
int[] top = new int[board.length];
Arrays.fill(top, 0);
for(int i=0; i<board.length; i++){
for(int j=0; j<board.length; j++){
if(board[j][i]==0){
top[i]++;
}else break;
}
}
System.out.println(Arrays.toString(top));
for(int m: moves) {
if(top[m-1] == board.length) { // board[top[m-1]][m-1]위치에 인형이 없음
continue;
}
if(stack.size()==0) { //바구니가 비어 있음
stack.push( board[top[m-1]][m-1]);
top[m-1]++;
continue;
}else {
if(stack.peek() == board[top[m-1]][m-1]) { //동일한 인형
stack.pop();
top[m-1]++;
count++;
}else {
stack.push( board[top[m-1]][m-1] );
top[m-1]++;
}
}
}
return count*2;
}
}
'IT > 알고리즘' 카테고리의 다른 글
[프로그래머스] 신고결과 받기 (0) | 2022.06.18 |
---|---|
[프로그래머스] 로또의 최고 순위와 최저 순위 (0) | 2022.06.15 |
[프로그래머스] 3진법 뒤집기 (0) | 2022.06.11 |
[프로그래머스] 모의고사 (0) | 2022.06.11 |
[프로그래머스] 실패율 (0) | 2022.06.02 |
Comments