1일1알

백준 1261번 알고스팟 C++ 본문

알고리즘

백준 1261번 알고스팟 C++

영춘권의달인 2022. 8. 11. 09:45

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

 

앞에 벽이 있거나 없는 경우가 있다. 있으면 벽을 부수고 없으면 그냥 간다. 구해야 하는 답은 벽을 최소 몇 개 부수어야 하는지 이기 때문에 bfs로 탐색할 때 벽을 부순 횟수가 가장 적은 경우가 가장 앞에 있어야 한다. 그렇기 때문에 우선순위 큐를 사용해서 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, m;

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

struct Vertex {
    int row;
    int col;
    int cnt;

    bool operator<(const Vertex& other) const {
        return cnt < other.cnt;
    }

    bool operator>(const Vertex& other) const {
        return cnt > other.cnt;
    }
};

vector<vector<int>> board;
vector<vector<bool>> found;

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

    cin >> m >> n;
    board = vector<vector<int>>(n, vector<int>(m));
    found = vector<vector<bool>>(n, vector<bool>(m, false));
    for (int i = 0; i < n; i++) {
        string str;
        cin >> str;
        for (int j = 0; j < m; j++) {
            board[i][j] = str[j] - '0';
        }
    }
    priority_queue<Vertex, vector<Vertex>, greater<Vertex>> pq;
    pq.push({ 0,0,0 });
    found[0][0] = true;
    int ans = 0;
    while (!pq.empty()) {
        auto curr = pq.top();
        pq.pop();
        if (curr.row == n - 1 && curr.col == m - 1) {
            ans = curr.cnt;
            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 >= m) continue;
            if (found[nextRow][nextCol]) continue;
            if (board[nextRow][nextCol] == 1) {
                board[nextRow][nextCol] = 0;
                found[nextRow][nextCol] = true;
                pq.push({ nextRow,nextCol,curr.cnt + 1 });
            }
            else {
                found[nextRow][nextCol] = true;
                pq.push({ nextRow,nextCol,curr.cnt });
            }
        }
    }
    cout << ans;
}