[アルゴリズム]プログラマー-クレーン型綱引きゲーム/Java

6731 ワード

import java.io.*;
import java.util.*;

class Solution {
    public int solution(int[][] board, int[] moves) {
        Stack<Integer> stack = new Stack<>();
        int size =  board.length; 
        int answer = 0;
        
        
        //moves
        for( int k = 0 ; k < moves.length ; k++){      
            int temp = moves[k];
            for(int i = 0 ; i < size ; i ++){
                if(board[i][temp-1] != 0){
                    if(!stack.isEmpty() && stack.peek() == board[i][temp-1]){
                        answer+= 2;        
                        stack.pop();
                    }else{
                        stack.push(board[i][temp-1]);
                    }
                    board[i][temp-1] = 0;
                    break;
                }
            }
        }
     
    
        return answer;
    }
}