알고리즘
백준 14442번 벽 부수고 이동하기 2 C++
영춘권의달인
2022. 9. 21. 10:00
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;
}