Close
Close full mode
logo만렙 개발자 키우기

크레인 인형뽑기 게임

Git RepositoryEdit on Github
Last update: a year ago by nowwaterReading time: 2 min

문제

코드

코드 보기
import java.util.Scanner;
import java.util.Stack;
public class intern20191 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int [][] board = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = sc.nextInt();
}
}
int moves[] = new int[m];
for (int i = 0; i < m; i++) {
moves[i] = sc.nextInt();
}
Solution solution = new Solution();
System.out.println(solution.solution(board, moves));
}
}
class Solution {
public int solution(int[][] board, int[] moves) {
int answer = 0, n = board.length, m = moves.length;
Stack<Integer> bucket = new Stack<>();
Stack<Integer> st[] = new Stack[n + 1];
for (int i = 1; i <= n; i++) {
st[i] = new Stack<>();
}
for (int i = n - 1; i >= 0; --i) {
for (int j = 0; j < n; ++j) {
if(board[i][j] != 0)
st[j + 1].push(board[i][j]);
}
}
for (int i = 0; i < moves.length; i++) {
int next = moves[i];
if(st[next].isEmpty()) continue;
int top = st[next].pop();
if(!bucket.isEmpty() && bucket.peek() == top) {
bucket.pop();
answer += 2;
}
else bucket.add(top);
}
return answer;
}
}

⭐️느낀점⭐️

스택 자료구조를 연습해볼 수 있어 좋았다.

풀이 📣


1️⃣ 보드의 아래쪽부터 탐색하면서 각 열에 대한 스택을 만들어서 저장해준다.

- Stack<Integer> st

2️⃣ 주어진 순서대로 열의 가장 위쪽에 위치한 인형을 바구니로 옮겨 담는다. 따라서 바구니도 스택 자료구조를 이용하면 된다.

3️⃣ 만약 바구니에 같은 인형이 연속으로 두 개 담기게 되면, 바구니에서 인형을 삭제하고 삭제한 인형 개수만큼 정답을 증가시켜준다.

4️⃣ 최종적으로 구한 정답을 출력한다.


실수 😅

  • 보드를 위에서부터 탐색하면서 스택에 넣어서 스택을 잘못쓰는건가 헷갈렸다.

  • 컬렉션 자료구조에 대해 확실히 알지 못해서 생긴 큰 실수였다.

👩‍💻 Problem Solving — Previous
12971
Next — 👩‍💻 Problem Solving
튜플