1일1알

백준 14442번 벽 부수고 이동하기 2 C++ 본문

알고리즘

백준 14442번 벽 부수고 이동하기 2 C++

영춘권의달인 2022. 9. 21. 10:00

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

 

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 n, m, k;

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

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

vector<vector<int>> board;
vector<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<vector<bool>>>(n, vector<vector<bool>>(m, vector<bool>(k + 1, 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';
        }
    }

    queue<Info> q;
    q.push({ 0,0,0,1 });
    found[0][0][0] = true;

    int ans = -1;

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

        if (curr.row == n - 1 && curr.col == m - 1) {
            ans = curr.moveCnt;
            break;
        }

        for (int i = 0; i < 4; i++) {
            int nextBreakCnt = curr.breakCnt;
            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) nextBreakCnt += 1;
            if (nextBreakCnt > k) continue;
            if (found[nextRow][nextCol][nextBreakCnt]) continue;
            q.push({ nextRow,nextCol,nextBreakCnt,curr.moveCnt+1 });
            found[nextRow][nextCol][nextBreakCnt] = true;
        }
    }

    cout << ans;
}

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

백준 1005번 ACM Craft C++  (1) 2022.09.26
백준 2252번 줄 세우기 C++  (1) 2022.09.23
백준 17396번 백도어 C++  (0) 2022.09.20
백준 1890번 점프 C++  (0) 2022.09.19
백준 17135번 캐슬 디펜스 C++  (0) 2022.09.18