주의할 점 : 처음에 인형이 존재할 때 , 그 사이에 공백이 있을 수 있다! 그래서 0이 보이면 break를 하는게 아니라, continue를 해야 한다!
일단 코드 먼저 ...
package section5.question3;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static int solution(int[][] board, int N, int[] moves, int M){
List<Stack<Integer>> stackList = new ArrayList<>();
for(int i=0; i<N; i++){
stackList.add(new Stack<>());
}
for(int i=0; i<N; i++){
for(int j=N-1; j>=0; j--){
if(board[j][i] == 0) {
continue;
}
stackList.get(i).push(board[j][i]);
}
}
int cnt = 0;
Stack<Integer> resultStack = new Stack<>();
/** 이부분은 resultStack에 push 하면서 바로바로 확인해서 빼주는 코드 -> 그런데 if~else가 너무 복잡하게 사용됨 ㅠ */
// for(int i=0; i<M; i++){
// if(resultStack.isEmpty()){
// if(!stackList.get(moves[i]-1).isEmpty()){
// resultStack.push(stackList.get(moves[i]-1).pop());
// } else {
// continue;
// }
// } else{
// if(!stackList.get(moves[i]-1).isEmpty()){
// if(resultStack.peek() == stackList.get(moves[i]-1).peek()){
// resultStack.pop();
// stackList.get(moves[i]-1).pop();
// cnt+=2;
// } else{
// resultStack.push(stackList.get(moves[i]-1).pop());
// }
// } else {
// continue;
// }
// }
// }
/** 이부분은 일단 resultStack에 다 옮겨놓고 , mask operation으로 같은 element들을 뺴주는 코드
* -> remove하면 그 이후 인덱스가 이전 인덱스가 된다는점과 , 반복을 위해 endFlag를 사용한 점이 point */
for(int i=0; i<M; i++){
if(!stackList.get(moves[i]-1).isEmpty()) {
resultStack.push(stackList.get(moves[i] - 1).pop());
}
}
List<Integer> resultList = new ArrayList<>();
while(!resultStack.isEmpty()){
resultList.add(resultStack.pop());
}
while(true){
int endFlag = 1;
for(int i=0; i<resultList.size()-1; i++){
if(resultList.get(i) == resultList.get(i+1)){
cnt+=2;
resultList.remove(i);
resultList.remove(i);
endFlag = 0;
break;
}
}
if(endFlag == 1) break;
}
return cnt;
}
public static void main(String[] args) {
//0. Scanner 준비
Scanner sc = new Scanner(System.in);
//1. 입력
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();
}
//2. solution()을 호출하여 결과 반환
int result = solution(board, N, moves, M);
//3. 결과 출력
System.out.println(result);
}
}