N * N 행렬에 각각 캐릭터의 번호가 주어지면 Stack에 넣어서 같은 번호가 나오면 pop 하고 아니면 push 하는 쉬운 문제였다.

#include <string>
#include <stack>
#include <vector>
using namespace std;
int pick(vector<vector<int>>& board, int col) {
for (int i = 0; i < board.size(); i++) {
if (board[i][col] == 0) continue;
int ret = board[i][col];
board[i][col] = 0;
return ret;
}
return 0;
}
int solution(vector<vector<int>> board, vector<int> moves) {
int answer = 0;
stack<int> s;
for (int i = 0; i < moves.size(); i++) {
int tmp = pick(board, moves[i] - 1);
if (tmp) {
if (s.empty()) s.push(tmp);
else {
if (s.top() == tmp) {
answer += 2;
s.pop();
}
else s.push(tmp);
}
}
}
return answer;
}
나는 moves 수만큼 pick 함수를 사용해서 넣어줬다. 처음에는
int pick(vector<vector<int>>& board, int col) {
for (int i = 0; i < board.size(); i++) {
if (board[i][col] == 0) continue;
int ret = board[i][col];
board[i][col] = 0;
return ret;
}
return 0;
}
이 pick 함수에서 board[col][i] 로 해야 되는 줄 알았는데 반대여서 틀렸었다;;
board에서 뽑았으면 그 후 0으로 바꿔줘야 다음번에 다시 뽑지 않는다.
'Programmers' 카테고리의 다른 글
[프로그래머스 C++] 카카오프렌즈 컬러링북 (0) | 2020.09.28 |
---|---|
[프로그래머스 C++] 소수 찾기 (0) | 2020.09.27 |
[프로그래머스 C++] 완주하지 못한 선수 (0) | 2020.09.26 |
[프로그래머스 C++] 모의고사 (0) | 2020.09.26 |
[프로그래머스 C++] 두 개 뽑아서 더하기 (0) | 2020.09.26 |