1일1알

백준 2665번 미로만들기 C++ 본문

알고리즘

백준 2665번 미로만들기 C++

영춘권의달인 2022. 8. 26. 10:08

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

우선순위 큐로 부신 방이 적을수록 먼저 빠져나오게 해서 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 n;
vector<vector<int>> board;
vector<vector<bool>> found;

int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };

pair<int, int> start;
pair<int, int> target;

struct RoomInfo {
    int row;
    int col;
    int breakCnt;

    bool operator<(const RoomInfo& other) const {
        return breakCnt > other.breakCnt;
    }
    bool operator>(const RoomInfo& other) const {
        return breakCnt < other.breakCnt;
    }
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cin >> n;
    start = { 0,0 };
    target = { n - 1,n - 1 };
    board = vector<vector<int>>(n, vector<int>(n));
    found = vector<vector<bool>>(n, vector<bool>(n, false));
    for (int i = 0; i < n; i++) {
        string str;
        cin >> str;
        for (int j = 0; j < n; j++) {
            board[i][j] = str[j] - '0';
        }
    }
    priority_queue<RoomInfo> pq;
    pq.push({ start.first,start.second,0 });
    found[start.first][start.second] = true;
    int ans = 0;
    while (!pq.empty()) {
        auto curr = pq.top();
        pq.pop();
        if (curr.row == target.first && curr.col == target.second) {
            ans = curr.breakCnt;
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nextRow = curr.row + dRow[i];
            int nextCol = curr.col + dCol[i];
            if (nextRow < 0 || nextRow >= n) continue;
            if (nextCol < 0 || nextCol >= n) continue;
            if (found[nextRow][nextCol]) continue;
            if (board[nextRow][nextCol] == 0)
                pq.push({ nextRow,nextCol,curr.breakCnt + 1 });
            else
                pq.push({ nextRow,nextCol,curr.breakCnt });
            found[nextRow][nextCol] = true;
        }
    }
    cout << ans;
}

'알고리즘' 카테고리의 다른 글

백준 10282번 해킹 C++  (0) 2022.08.29
백준 17836번 공주님을 구해라! C++  (0) 2022.08.28
백준 16637번 괄호 추가하기 C++  (0) 2022.08.23
백준 2661번 좋은수열 C++  (0) 2022.08.22
백준 4179번 불! C++  (0) 2022.08.21