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
- 다이나믹 프로그래밍
- 그리디 알고리즘
- 백트래킹
- 스택
- 유니티
- 누적 합
- 시뮬레이션
- Team Fortress 2
- c++
- 우선순위 큐
- 수학
- XR Interaction Toolkit
- 그래프
- 문자열
- 브루트포스
- DFS
- 투 포인터
- 백준
- BFS
- 구현
- 트리
- VR
- Unreal Engine 5
- 알고리즘
- ue5
- 유니온 파인드
- 재귀
- 다익스트라
- 자료구조
- 정렬
Archives
- Today
- Total
1일1알
백준 4991번 로봇 청소기 C++ 본문
어떤 더러운 칸들을 청소했는지를 비트로 관리하고 방문 표시를 3차원 배열(비트, 행, 열) 로 관리해서 bfs 탐색을 이용해서 풀었다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int r, c;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
struct Info {
int row;
int col;
int dirtyBit;
int moveCnt;
};
vector<vector<char>> board;
vector<vector<vector<bool>>> found;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
while (true) {
cin >> c >> r;
if (r == 0 && c == 0)
break;
board = vector<vector<char>>(r, vector<char>(c));
int dirtyCnt = 0;
pair<int, int> start;
map<pair<int, int>, int> pos2Bit;
for (int i = 0; i < r; i++) {
string str;
cin >> str;
for (int j = 0; j < c; j++) {
board[i][j] = str[j];
if (str[j] == 'o')
start = { i,j };
else if (str[j] == '*') {
int bit = 1 << dirtyCnt;
pos2Bit.insert({ {i,j},bit });
dirtyCnt++;
}
}
}
int targetBit = pow(2, dirtyCnt) - 1;
found = vector<vector<vector<bool>>>(pow(2, dirtyCnt), vector<vector<bool>>(r, vector<bool>(c, false)));
queue<Info> q;
q.push({ start.first,start.second,0,0 });
found[0][start.first][start.second] = true;
int ans = -1;
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (curr.dirtyBit == targetBit) {
ans = curr.moveCnt;
break;
}
for (int i = 0; i < 4; i++) {
int nextRow = curr.row + dRow[i];
int nextCol = curr.col + dCol[i];
if (nextRow < 0 || nextRow >= r) continue;
if (nextCol < 0 || nextCol >= c) continue;
if (board[nextRow][nextCol] == 'x') continue;
int nextBit = curr.dirtyBit;
if (board[nextRow][nextCol] == '*') {
if ((nextBit & pos2Bit[{nextRow, nextCol}]) == 0) {
nextBit |= pos2Bit[{nextRow, nextCol}];
}
}
if (found[nextBit][nextRow][nextCol]) continue;
q.push({ nextRow,nextCol,nextBit,curr.moveCnt + 1 });
found[nextBit][nextRow][nextCol] = true;
}
}
cout << ans << "\n";
}
}
'알고리즘' 카테고리의 다른 글
백준 13460번 구슬 탈출 2 C++ (0) | 2022.08.01 |
---|---|
백준 15685번 드래곤 커브 C++ (0) | 2022.07.31 |
백준 3197번 백조의 호수 C++ (0) | 2022.07.25 |
백준 2310번 어드벤처 게임 C++ (0) | 2022.07.24 |
백준 16946번 벽 부수고 이동하기 4 C++ (0) | 2022.07.23 |