1일1알

백준 25307번 시루의 백화점 구경 C++ 본문

알고리즘

백준 25307번 시루의 백화점 구경 C++

영춘권의달인 2022. 9. 17. 10:52

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

 

처음에 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>

#include <bitset>

using namespace std;
using int64 = long long;

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

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

int n, m, k;

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

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

    cin >> n >> m >> k;
    board = vector<vector<int>>(n, vector<int>(m));
    found = vector<vector<bool>>(n, vector<bool>(m, false));

    Info start;

    queue<Info> q;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> board[i][j];
            if (board[i][j] == 3) {
                q.push({ i,j,0 });
                found[i][j] = true;
            }
            else if (board[i][j] == 4) start = { i,j,0 };
        }
    }

    while (!q.empty()) {
        auto curr = q.front();
        q.pop();

        if (curr.moveCnt == k) continue;

        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;
            board[nextRow][nextCol] = 3;
            found[nextRow][nextCol] = true;
            q.push({ nextRow,nextCol,curr.moveCnt + 1 });
        }
    }

    for (auto a : found)
        for (auto b : a)
            b = false;

    q.push(start);
    found[start.row][start.col] = true;

    int ans = -1;
    while (!q.empty()) {
        auto curr = q.front();
        q.pop();

        if (board[curr.row][curr.col] == 2) {
            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 >= n) continue;
            if (nextCol < 0 || nextCol >= m) continue;
            if (board[nextRow][nextCol] == 1) continue;
            if (board[nextRow][nextCol] == 3) continue;
            if (found[nextRow][nextCol]) continue;
            found[nextRow][nextCol] = true;
            q.push({ nextRow,nextCol,curr.moveCnt + 1 });
        }
    }
    cout << ans;
}

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

백준 1890번 점프 C++  (0) 2022.09.19
백준 17135번 캐슬 디펜스 C++  (0) 2022.09.18
백준 19238번 스타트 택시 C++  (0) 2022.09.16
백준 3273번 두 수의 합 C++  (0) 2022.09.15
백준 2437번 저울 C++  (1) 2022.09.14