[BOJ] 달이 차오른다, 가자.
Date:
[BOJ] 달이 차오른다, 가자.
Problem URL : 달이 차오른다, 가자.
#include<iostream>
#include<queue>
#include<string>
#define MAX 50
using namespace std;
int n, m;
char map[MAX][MAX];
bool visit[MAX][MAX][1 << 6]; // 6개의 key에 대한 비트마스크
pair<int, int> start;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
// 움직일 때 미로 각각의 격자에서의 정보
struct Info {
int x;
int y;
int cnt;
int key;
Info(int _x, int _y, int _cnt, int _key) : x(_x), y(_y), cnt(_cnt), key(_key) {};
};
bool hasKey(int key, char door) {
int hasKey = key & (1 << (int(door) - 'A'));
return hasKey != 0;
}
int bfs(int a, int b) {
queue<Info> q;
visit[a][b][0] = true;
q.push(Info(a,b,0,0));
while (q.empty() == 0) {
int x = q.front().x;
int y = q.front().y;
int cnt = q.front().cnt;
int key = q.front().key;
q.pop();
if (map[x][y] == '1') return cnt;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || ny < 0 || nx >= n || ny >= m || visit[nx][ny][key]) {
continue;
}
if (map[nx][ny] == '.' || map[nx][ny] == '1') {
visit[nx][ny][key] = true;
q.push(Info(nx, ny, cnt + 1, key));
} else if ('a' <= map[nx][ny] && map[nx][ny] <= 'f') {
int tmpKey = key | (1 << (int(map[nx][ny] - 'a')));
visit[nx][ny][tmpKey] = true;
q.push(Info(nx, ny, cnt + 1, tmpKey));
} else if ('A' <= map[nx][ny] && map[nx][ny] <= 'F') {
if (hasKey(key, map[nx][ny])){
visit[nx][ny][key] = true;
q.push(Info(nx, ny, cnt + 1, key));
}
}
}
}
return -1;
}
int main(void) {
ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++) {
string input;
cin >> input;
for (int j = 0; j < m; j++) {
map[i][j] = input[j];
if (map[i][j] == '0') {
start.first = i;
start.second = j;
map[i][j] = '.';
}
}
}
cout << bfs(start.first, start.second) << endl;
return 0;
}
댓글