(백준 13460번) 구슬 탈출 2
문제 설명
스타트링크에서 판매하는 어린이용 장난감 중에서 가장 인기가 많은 제품은 구슬 탈출이다. 구슬 탈출은 직사각형 보드에 빨간 구슬과 파란 구슬을 하나씩 넣은 다음, 빨간 구슬을 구멍을 통해 빼내는 게임이다.
보드의 세로 크기는 N, 가로 크기는 M이고, 편의상 1×1크기의 칸으로 나누어져 있다. 가장 바깥 행과 열은 모두 막혀져 있고, 보드에는 구멍이 하나 있다. 빨간 구슬과 파란 구슬의 크기는 보드에서 1×1크기의 칸을 가득 채우는 사이즈이고, 각각 하나씩 들어가 있다. 게임의 목표는 빨간 구슬을 구멍을 통해서 빼내는 것이다. 이때, 파란 구슬이 구멍에 들어가면 안 된다.
이때, 구슬을 손으로 건드릴 수는 없고, 중력을 이용해서 이리 저리 굴려야 한다. 왼쪽으로 기울이기, 오른쪽으로 기울이기, 위쪽으로 기울이기, 아래쪽으로 기울이기와 같은 네 가지 동작이 가능하다.
각각의 동작에서 공은 동시에 움직인다. 빨간 구슬이 구멍에 빠지면 성공이지만, 파란 구슬이 구멍에 빠지면 실패이다. 빨간 구슬과 파란 구슬이 동시에 구멍에 빠져도 실패이다. 빨간 구슬과 파란 구슬은 동시에 같은 칸에 있을 수 없다. 또, 빨간 구슬과 파란 구슬의 크기는 한 칸을 모두 차지한다. 기울이는 동작을 그만하는 것은 더 이상 구슬이 움직이지 않을 때 까지이다.
보드의 상태가 주어졌을 때, 최소 몇 번 만에 빨간 구슬을 구멍을 통해 빼낼 수 있는지 구하는 프로그램을 작성하시오.
입력
첫 번째 줄에는 보드의 세로, 가로 크기를 의미하는 두 정수 N, M (3 ≤ N, M ≤ 10)이 주어진다. 다음 N개의 줄에 보드의 모양을 나타내는 길이 M의 문자열이 주어진다. 이 문자열은 ‘.’, ‘#’, ‘O’, ‘R’, ‘B’ 로 이루어져 있다. ‘.’은 빈 칸을 의미하고, ‘#’은 공이 이동할 수 없는 장애물 또는 벽을 의미하며, ‘O’는 구멍의 위치를 의미한다. ‘R’은 빨간 구슬의 위치, ‘B’는 파란 구슬의 위치이다.
입력되는 모든 보드의 가장자리에는 모두 ‘#’이 있다. 구멍의 개수는 한 개 이며, 빨간 구슬과 파란 구슬은 항상 1개가 주어진다.
출력
최소 몇 번 만에 빨간 구슬을 구멍을 통해 빼낼 수 있는지 출력한다. 만약, 10번 이하로 움직여서 빨간 구슬을 구멍을 통해 빼낼 수 없으면 -1을 출력한다.
문제 풀이
미로를 구현한 행렬 안에서 구슬이나 블럭을 굴리는 문제이고 많이 풀어 봤던 유형이지만 백트래킹과 예외 처리가 필요한 만큼 훨씬 어렵고 실수할 여지가 많은 고난이도 문제였다.
10번까지 움직일 수 있으므로 백트래킹을 이용하여 판을 기울이는 모든 경우의 수를 탐색했는데, 예를 들어 구슬이 …RB 와 같이 되어있을 때 판을 왼쪽으로 기울인다고 가정하면 파란 구슬을 먼저 굴리면 바로 옆에 있는 R구슬에 막혀 제대로 된 값이 나오지 않게 된다. 그러므로 각 구슬의 x값과 y값을 비교하여 왼쪽으로 기울일 땐 더 왼쪽에 있는 구슬을 먼저 굴리도록 구현하였는데, 이 과정에서 코드의 길이가 두 배로 늘어났다.
bfs로도 풀 수 있다고 하여 다른 사람들의 풀이를 살펴보았는데, visited 배열을 구슬이 2개이므로 4차원 배열로 가져가는 방식으로 풀어내어 내 풀이보다 훨씬 코드가 깔끔하고 빠른 시간에 작동하는 풀이였다. 아마 이것이 정답으로 의도한 풀이가 아닐까 싶었다.
시간 제한 2초에 1076ms로 통과하였는데, bfs 풀이를 생각해내지 못했던 만큼 시간제한이 더 촉박했더라면 풀기 힘들지 않았을까 싶은 문제였다.
# 코드
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int n, m;
int mini=100000;
bool oob(int x, int y) {
if(x>=0 && x<n && y>=0 && y<m) return true;
return false;
}
void backtrack(vector<vector<char>> table, int count, pair<int,int> r, pair<int,int> b) {
vector<vector<char>> tmp=table; bool r_pass=false; bool b_pass=false;
pair<int,int> nr=r; pair<int,int> nb=b;
if(count==10) return;
if(r.second<=b.second) {
for(int i=r.second-1; i>=0; i--) {
if(oob(r.first,i)) {
if(tmp[r.first][i]=='#') {
tmp[r.first][r.second]='.'; tmp[r.first][i+1]='R';
nr={r.first,i+1}; break;
}
else if(tmp[r.first][i]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
for(int i=b.second-1; i>=0; i--) {
if(oob(b.first,i)) {
if(tmp[b.first][i]=='#' || tmp[b.first][i]=='R') {
tmp[b.first][b.second]='.'; tmp[b.first][i+1]='B';
nb={b.first,i+1}; break;
}
else if(tmp[b.first][i]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
else if(r.second>b.second) {
for(int i=b.second-1; i>=0; i--) {
if(oob(b.first,i)) {
if(tmp[b.first][i]=='#') {
tmp[b.first][b.second]='.'; tmp[b.first][i+1]='B';
nb={b.first,i+1}; break;
}
else if(tmp[b.first][i]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
for(int i=r.second-1; i>=0; i--) {
if(oob(r.first,i)) {
if(tmp[r.first][i]=='#' || tmp[r.first][i]=='B') {
tmp[r.first][r.second]='.'; tmp[r.first][i+1]='R';
nr={r.first,i+1}; break;
}
else if(tmp[r.first][i]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
if(!r_pass && !b_pass) {
backtrack(tmp,count+1,nr,nb);
}
tmp=table; r_pass=false; b_pass=false; nr=r; nb=b;
if(r.second<=b.second) {
for(int i=b.second+1; i<m; i++) {
if(oob(b.first,i)) {
if(tmp[b.first][i]=='#') {
tmp[b.first][b.second]='.'; tmp[b.first][i-1]='B';
nb={b.first,i-1}; break;
}
else if(tmp[b.first][i]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
for(int i=r.second+1; i<m; i++) {
if(oob(r.first,i)) {
if(tmp[r.first][i]=='#' || tmp[r.first][i]=='B') {
tmp[r.first][r.second]='.'; tmp[r.first][i-1]='R';
nr={r.first,i-1}; break;
}
else if(tmp[r.first][i]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
else if(r.second>b.second) {
for(int i=r.second+1; i<m; i++) {
if(oob(r.first,i)) {
if(tmp[r.first][i]=='#') {
tmp[r.first][r.second]='.'; tmp[r.first][i-1]='R';
nr={r.first,i-1}; break;
}
else if(tmp[r.first][i]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
for(int i=b.second+1; i<m; i++) {
if(oob(b.first,i)) {
if(tmp[b.first][i]=='#' || tmp[b.first][i]=='R') {
tmp[b.first][b.second]='.'; tmp[b.first][i-1]='B';
nb={b.first,i-1}; break;
}
else if(tmp[b.first][i]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
if(!r_pass && !b_pass) {
backtrack(tmp,count+1,nr,nb);
}
tmp=table; r_pass=false; b_pass=false; nr=r; nb=b;
if(r.first<=b.first) {
for(int i=r.first-1; i>=0; i--) {
if(oob(i,r.second)) {
if(tmp[i][r.second]=='#') {
tmp[r.first][r.second]='.'; tmp[i+1][r.second]='R';
nr={i+1,r.second}; break;
}
else if(tmp[i][r.second]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
for(int i=b.first-1; i>=0; i--) {
if(oob(i,b.second)) {
if(tmp[i][b.second]=='#' || tmp[i][b.second]=='R') {
tmp[b.first][b.second]='.'; tmp[i+1][b.second]='B';
nb={i+1,b.second}; break;
}
else if(tmp[i][b.second]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
else if(r.first>b.first) {
for(int i=b.first-1; i>=0; i--) {
if(oob(i,b.second)) {
if(tmp[i][b.second]=='#') {
tmp[b.first][b.second]='.'; tmp[i+1][b.second]='B';
nb={i+1,b.second}; break;
}
else if(tmp[i][b.second]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
for(int i=r.first-1; i>=0; i--) {
if(oob(i,r.second)) {
if(tmp[i][r.second]=='#' || tmp[i][r.second]=='B') {
tmp[r.first][r.second]='.'; tmp[i+1][r.second]='R';
nr={i+1,r.second}; break;
}
else if(tmp[i][r.second]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
if(!r_pass && !b_pass) {
backtrack(tmp,count+1,nr,nb);
}
tmp=table; r_pass=false; b_pass=false; nr=r; nb=b;
if(r.first<=b.first) {
for(int i=b.first+1; i<n; i++) {
if(oob(i,b.second)) {
if(tmp[i][b.second]=='#') {
tmp[b.first][b.second]='.'; tmp[i-1][b.second]='B';
nb={i-1,b.second}; break;
}
else if(tmp[i][b.second]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
for(int i=r.first+1; i<n; i++) {
if(oob(i,r.second)) {
if(tmp[i][r.second]=='#' || tmp[i][r.second]=='B') {
tmp[r.first][r.second]='.'; tmp[i-1][r.second]='R';
nr={i-1,r.second}; break;
}
else if(tmp[i][r.second]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
else if(r.first>b.first) {
for(int i=r.first+1; i<n; i++) {
if(oob(i,r.second)) {
if(tmp[i][r.second]=='#') {
tmp[r.first][r.second]='.'; tmp[i-1][r.second]='R';
nr={i-1,r.second}; break;
}
else if(tmp[i][r.second]=='O') {
tmp[r.first][r.second]='.'; r_pass=true; break;
}
}
}
for(int i=b.first+1; i<n; i++) {
if(oob(i,b.second)) {
if(tmp[i][b.second]=='#' || tmp[i][b.second]=='R') {
tmp[b.first][b.second]='.'; tmp[i-1][b.second]='B';
nb={i-1,b.second}; break;
}
else if(tmp[i][b.second]=='O') {
tmp[b.first][b.second]='.'; b_pass=true; break;
}
}
}
if(r_pass && !b_pass) {
if(mini>count) mini=count;
return;
}
}
if(!r_pass && !b_pass) {
backtrack(tmp,count+1,nr,nb);
}
}
int main() {
cin >> n >> m;
vector<vector<char>> v;
pair<int,int> red;
pair<int,int> blue;
for(int i=0; i<n; i++) {
vector<char> tmp;
for(int j=0; j<m; j++) {
char c; cin >> c; tmp.push_back(c);
if(c=='R') red={i,j};
else if(c=='B') blue={i,j};
}
v.push_back(tmp);
}
backtrack(v, 0, red, blue);
if(mini==100000) cout << -1;
else cout << mini+1;
}