1일1알

백준 4485번 녹색 옷 입은 애가 젤다지? C++ 본문

알고리즘

백준 4485번 녹색 옷 입은 애가 젤다지? C++

영춘권의달인 2022. 8. 16. 11:29

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

 

우선순위 큐를 사용해서 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 };

struct Info {
    pair<int, int> pos;
    int penalty;
    bool operator<(const Info& other) const {
        return penalty < other.penalty;
    }
    bool operator>(const Info& other) const {
        return penalty > other.penalty;
    }
};

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

    int cnt = 1;
    while (true) {
        cin >> n;
        if (n == 0) break;
        board = vector<vector<int>>(n, vector<int>(n));
        found = vector<vector<bool>>(n, vector<bool>(n, false));
        pair<int, int> targetPos = { n - 1,n - 1 };
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cin >> board[i][j];
            }
        }
        priority_queue<Info, vector<Info>, greater<Info>> pq;
        pq.push({ {0,0},board[0][0] });
        found[0][0] = true;
        int ans = 0;
        while (!pq.empty()) {
            auto curr = pq.top();
            pq.pop();
            if (curr.pos == targetPos) {
                ans = curr.penalty;
                break;
            }
            for (int i = 0; i < 4; i++) {
                int nextRow = curr.pos.first + dRow[i];
                int nextCol = curr.pos.second + dCol[i];
                if (nextRow < 0 || nextRow >= n) continue;
                if (nextCol < 0 || nextCol >= n) continue;
                if (found[nextRow][nextCol]) continue;
                pq.push({ {nextRow,nextCol},curr.penalty + board[nextRow][nextCol] });
                found[nextRow][nextCol] = true;
            }
        }
        cout << "Problem " << cnt << ": " << ans << "\n";
        cnt++;
    }
}