-
#17244 아맞다우산Code/BOJ 2020. 1. 3. 12:59728x90반응형
출처:https://www.acmicpc.net/problem/17244
17244번: 아맞다우산
경재씨는 저녁 약속을 가기 전 챙기지 않은 물건들이 있는 지 확인하고 있다. 필요한 물건은 전부 챙긴 것 같았고 외출 후 돌아오는 길에 경재씨는 외쳤다. "아 맞다 우산!!!" 경재 씨는 매번 외출하고 나서야 어떤 물건을 집에 놓고 왔다는 것을 떠올릴 때마다 자책감에 시달리는 것이 너무 싫었다. 외출이 잦은 경재 씨는 반복되는 일을 근절하기 위해 꼭 챙겨야 할 물건들을 정리해보았다. 하지만 지갑, 스마트폰, 우산, 차 키, 이어폰, 시계, 보조 배터리 등
www.acmicpc.net
위 그림과 같이 입력값이 주어져 S에서 출발하여 물건X를 모두 수집하고 E로 도착하기 위한 최단 경로를 구하는 문제이다. 비트마스킹을 이용하여 visit[x][y][key(보유 키 현황)]배열을 생성하였고 bfs를 통해 구현하였다.
예를 들어 보유한 키가 0번 1번이면 00001 | 00010 = 00011 이 키 보유 현황이 되고 이때의 visit에서 bfs를 통해 새로운 키나 목적지를 찾아가게 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters// #17244 아맞다우산 #include <iostream> #include <queue> #define endl '\n' #include <cstring> using namespace std; char arr[52][52]; int visit[51][51][1<<5]; int n,m,keyn; int stx, sty, edx, edy; int dir[4][2] = { {1,0}, { 0,1 }, { -1,0 }, { 0,-1 } }; typedef struct xy { int x, y,key; }xy; int bfs(int x,int y) { queue<xy> q; int key = 0; q.push({ x,y,key }); visit[x][y][key] = true; int TIME = 0; while (!q.empty()) { int size = q.size(); while (size--) { int fx = q.front().x, fy = q.front().y,fkey=q.front().key; q.pop(); //cout << "fx " << fx << " fy " << fy << " fkey " << fkey << endl; if (arr[fx][fy] == 'E'&&fkey == (1 << keyn) - 1) {///열쇠를 모두 수집한 상태 return TIME; } for (int d = 0; d < 4; d++) { int nx = fx + dir[d][0], ny = fy + dir[d][1], nkey = fkey; if (nx < 0 || nx >= n || ny < 0 || ny >= m)continue; if (visit[nx][ny][nkey])continue; if (arr[nx][ny] == '#')continue; if ('0' <= arr[nx][ny] && arr[nx][ny] <= '4') { nkey |= (1 << (arr[nx][ny] - '0')); } visit[nx][ny][nkey] = true; q.push({ nx,ny,nkey }); } } TIME++; } } int main() { cin.tie(0); cin.sync_with_stdio(0); cin >> m >> n; keyn = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> arr[i][j]; if (arr[i][j] == 'S') { stx = i, sty = j; } else if (arr[i][j] == 'X') { arr[i][j] = keyn+'0'; keyn++; } else if (arr[i][j] == 'E') { edx = i, edy = j; } } } cout<<bfs(stx, sty)<<endl; } 728x90반응형'Code > BOJ' 카테고리의 다른 글
#17836 공주님을 구해라! (0) 2020.01.05 #9328 열쇠 (0) 2020.01.05 #2096 내려가기 (0) 2020.01.02 #1917 정육면체 전개도 (0) 2020.01.02 #2098 외판원 순회 (0) 2020.01.01