알고리즘
백준 2206번 벽 부수고 이동하기 C++
영춘권의달인
2022. 2. 28. 12:05
동일한 지점에 늦게 도착하더라도 벽을 부술 수 있는 기회가 남아있으면 벽을 부수지 못하는 먼저 도착한 경우보다 먼저 목적지까지 도달할 수 있기 때문에 방문 여부를 기록하는 배열을 벽을 부술 수 있는 상태에서 방문한 것과 부수지 못하는 상태에서 방문한 것 두 가지로 나눠서 문제를 해결하였다.
#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 <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
struct Info {
int row;
int col;
int dist;
int chance;
};
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
int n, m;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
vector<vector<int>> board(n, vector<int>(m));
vector<vector<bool>> visited_1(n, vector<bool>(m, false));
vector<vector<bool>> visited_2(n, vector<bool>(m, 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,1,1 });
visited_1[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.dist;
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 (curr.chance == 1) {
if (visited_1[nextRow][nextCol]) continue;
if (board[nextRow][nextCol] == 1) {
visited_1[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.dist + 1,curr.chance - 1 });
}
else {
visited_1[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.dist + 1,curr.chance });
}
}
else {
if (visited_2[nextRow][nextCol]) continue;
if (board[nextRow][nextCol] == 1) continue;
visited_2[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.dist + 1,curr.chance });
}
}
}
cout << ans;
};