1일1알

백준 17836번 공주님을 구해라! C++ 본문

알고리즘

백준 17836번 공주님을 구해라! C++

영춘권의달인 2022. 8. 28. 12:49

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

 

그람을 가지고 있을때와 없을때의 방문배열을 따로 두고 그람이 있을때는 벽을 통과할 수 있도록 해서 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, t;
pair<int, int> target;

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

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

struct Info {
    int row;
    int col;
    int moveCnt;
    int gram;
};

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

    cin >> n >> m >> t;
    target = { n - 1,m - 1 };
    board = vector<vector<int>>(n, vector<int>(m));
    found = vector<vector<vector<bool>>>(2, vector<vector<bool>>(n, vector<bool>(m, false)));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> board[i][j];
        }
    }
    queue<Info> q;
    q.push({ 0,0,0,0 });
    found[0][0][0] = true;
    int ans = t + 1;
    while (!q.empty()) {
        auto curr = q.front();
        q.pop();
        if (curr.row == target.first && curr.col == target.second) {
            ans = curr.moveCnt;
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nextRow = curr.row + dRow[i];
            int nextCol = curr.col + dCol[i];
            int nextGram = curr.gram;
            if (nextRow < 0 || nextRow >= n) continue;
            if (nextCol < 0 || nextCol >= m) continue;
            if (found[nextGram][nextRow][nextCol]) continue;
            if (board[nextRow][nextCol] == 1) {
                if (nextGram == 0) continue;
                q.push({ nextRow,nextCol,curr.moveCnt + 1,nextGram });
            }
            else {
                if (board[nextRow][nextCol] == 2) nextGram = 1;
                q.push({ nextRow,nextCol,curr.moveCnt + 1,nextGram });
            }
            found[nextGram][nextRow][nextCol] = true;
        }
    }
    if (ans <= t) cout << ans;
    else cout << "Fail";
}

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

백준 6497번 전력난 C++  (0) 2022.08.30
백준 10282번 해킹 C++  (0) 2022.08.29
백준 2665번 미로만들기 C++  (0) 2022.08.26
백준 16637번 괄호 추가하기 C++  (0) 2022.08.23
백준 2661번 좋은수열 C++  (0) 2022.08.22