Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- DFS
- XR Interaction Toolkit
- 유니온 파인드
- 다익스트라
- 구현
- 투 포인터
- 누적 합
- Unreal Engine 5
- 재귀
- 그리디 알고리즘
- c++
- 정렬
- 자료구조
- 알고리즘
- 유니티
- 문자열
- 우선순위 큐
- BFS
- VR
- 브루트포스
- 다이나믹 프로그래밍
- 백트래킹
- 트리
- Team Fortress 2
- ue5
- 스택
- 수학
- 시뮬레이션
- 그래프
- 백준
Archives
- Today
- Total
1일1알
백준 16197번 두 동전 C++ 본문
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
int n, m;
vector<vector<char>> board;
vector<vector<vector<vector<bool>>>> found;
struct Coins {
pair<int, int> coin1;
pair<int, int> coin2;
int moveCnt;
};
int main()
{
cin >> n >> m;
board = vector<vector<char>>(n, vector<char>(m));
found = vector<vector<vector<vector<bool>>>>(n, vector<vector<vector<bool>>>(m, vector<vector<bool>>(n, vector<bool>(m, false))));
vector<pair<int, int>> initCoins;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> board[i][j];
if (board[i][j] == 'o') initCoins.push_back({ i,j });
}
}
pair<int, int> coin1 = initCoins[0];
pair<int, int> coin2 = initCoins[1];
queue<Coins> q;
q.push({ coin1,coin2,0 });
found[coin1.first][coin1.second][coin2.first][coin2.second] = true;
int ans = -1;
while (!q.empty()) {
auto curr = q.front();
q.pop();
bool finished = false;
for (int i = 0; i < 4; i++) {
int cnt = 0;
int nextRow1 = curr.coin1.first + dRow[i];
int nextCol1 = curr.coin1.second + dCol[i];
int nextRow2 = curr.coin2.first + dRow[i];
int nextCol2 = curr.coin2.second + dCol[i];
if (nextRow1 < 0 || nextRow1 >= n || nextCol1 < 0 || nextCol1 >= m) {
cnt++;
}
if (nextRow2 < 0 || nextRow2 >= n || nextCol2 < 0 || nextCol2 >= m) {
cnt++;
}
if (cnt == 2) continue;
if (cnt == 1) {
ans = curr.moveCnt + 1;
finished = true;
break;
}
if (board[nextRow1][nextCol1] == '#') {
nextRow1 = curr.coin1.first;
nextCol1 = curr.coin1.second;
}
if (board[nextRow2][nextCol2] == '#') {
nextRow2 = curr.coin2.first;
nextCol2 = curr.coin2.second;
}
if (found[nextRow1][nextCol1][nextRow2][nextCol2]) continue;
found[nextRow1][nextCol1][nextRow2][nextCol2] = true;
q.push({ {nextRow1,nextCol1},{nextRow2,nextCol2},curr.moveCnt + 1 });
}
if (finished) break;
}
if (ans > 10) ans = -1;
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 9466번 텀 프로젝트 C++ (0) | 2022.09.03 |
---|---|
백준 1520번 내리막 길 C++ (0) | 2022.09.02 |
백준 16562번 친구비 C++ (0) | 2022.08.31 |
백준 6497번 전력난 C++ (0) | 2022.08.30 |
백준 10282번 해킹 C++ (0) | 2022.08.29 |