1일1알

백준 5427번 불 C++ 본문

알고리즘

백준 5427번 불 C++

영춘권의달인 2022. 8. 18. 10:27

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

 

불이 붙으려는 칸으로 이동할 수 없다고 했기 때문에 큐에 불을 먼저 넣고 상근이의 위치를 넣은 뒤 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 w, h;
vector<vector<char>> board;
vector<vector<bool>> found;

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

enum Type {
    Player,
    Fire
};

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

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

    int t;
    cin >> t;
    while (t--) {
        cin >> w >> h;
        board = vector<vector<char>>(h, vector<char>(w));
        found = vector<vector<bool>>(h, vector<bool>(w, false));
        vector<pair<int, int>> fire;
        pair<int, int> start;
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                cin >> board[i][j];
                if (board[i][j] == '*')
                    fire.push_back({ i,j });
                else if (board[i][j] == '@')
                    start = { i,j };
            }
        }
        queue<Info> q;
        for (auto a : fire) {
            q.push({ a.first,a.second,0,Fire });
        }
        q.push({ start.first,start.second,0,Player });
        found[start.first][start.second] = true;
        int ans = -1;
        bool loop = true;
        while (!q.empty()) {
            auto curr = q.front();
            q.pop();
            for (int i = 0; i < 4; i++) {
                int nextRow = curr.row + dRow[i];
                int nextCol = curr.col + dCol[i];
                if (nextRow < 0 || nextRow >= h || nextCol < 0 || nextCol >= w) {
                    if (curr.type == Player) {
                        ans = curr.moveCnt + 1;
                        loop = false;
                        break;
                    }
                    continue;
                }
                if (board[nextRow][nextCol] == '#') continue;
                if (board[nextRow][nextCol] == '*') continue;
                if (curr.type == Fire) board[nextRow][nextCol] = '*';
                else {
                    if (found[nextRow][nextCol]) continue;
                    found[nextRow][nextCol] = true;
                }
                q.push({ nextRow,nextCol,curr.moveCnt + 1,curr.type });
            }
            if (!loop) break;
        }
        if (ans == -1) cout << "IMPOSSIBLE";
        else cout << ans;
        cout << "\n";
    }
}