1일1알

백준 4991번 로봇 청소기 C++ 본문

알고리즘

백준 4991번 로봇 청소기 C++

영춘권의달인 2022. 7. 26. 12:44

출처 : https://www.acmicpc.net/problem/4991

 

어떤 더러운 칸들을 청소했는지를 비트로 관리하고 방문 표시를 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";
    }
}