ALGORITHM
[JAVA] 알고리즘 : Stack- 크레인 인형뽑기(카카오)
연듀
2022. 7. 12. 09:36
import java.util.*;
public class Main {
public int solution(int[][] board, int[] moves) {
int answer = 0;
Stack<Integer> stack=new Stack<>();
for(int pos : moves){
for(int i=0; i<board.length; i++){ // 행의 길이만큼
if(board[i][pos-1]!=0){ // 인형이 존재하면
int tmp = board[i][pos-1];
board[i][pos-1]=0;
if(!stack.isEmpty() && tmp == stack.peek()){ // stack이 비어있지 않고 스택의 맨위의 인형과 같다면
answer+=2; // 인형 두개 터트림
stack.pop(); // 맨 위의 인형 제거
}
else stack.push(tmp); // 맨 위의 인형과 같지 않다면 스택에 push
break;
}
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n = 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 m = sc.nextInt();
int[] moves = new int[m];
for (int i = 0; i < m; i++) moves[i] = sc.nextInt();
System.out.println(T.solution(board,moves));
}
}
반응형