인프런 커뮤니티 질문&답변
break의 범위에는 차이가 없어보이는데 else 범위 안에 넣었을 때 왜 결과값이 다른지 추론이 안됩니다 ㅠㅠ 이유를 알고 싶습니다 !
작성
·
243
0
import java.util.*;
public class Main {
public int solution(int[][] board, int[] moves) {
int answer = 0;
Stack<Integer> stack = new Stack<Integer>();
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()) {
answer += 2;
stack.pop();
} else {
stack.push(tmp);
break;
}
}
}
}
return answer;
}
public static void main(String[] args) {
Main M = 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(M.solution(board, moves));
}
}답변 1
1
김태원
지식공유자
안녕하세요^^
else 안에 break를 넣으면
if(!stack.isEmpty() && tmp == stack.peek())
위에 코드가 참이되었을 때 break가 되지 않고 인형을 하나 더 꺼내버리게 됩니다.





