알고리즘
백준 2665번 미로만들기 C++
영춘권의달인
2022. 8. 26. 10:08
우선순위 큐로 부신 방이 적을수록 먼저 빠져나오게 해서 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 n;
vector<vector<int>> board;
vector<vector<bool>> found;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
pair<int, int> start;
pair<int, int> target;
struct RoomInfo {
int row;
int col;
int breakCnt;
bool operator<(const RoomInfo& other) const {
return breakCnt > other.breakCnt;
}
bool operator>(const RoomInfo& other) const {
return breakCnt < other.breakCnt;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
start = { 0,0 };
target = { n - 1,n - 1 };
board = vector<vector<int>>(n, vector<int>(n));
found = vector<vector<bool>>(n, vector<bool>(n, false));
for (int i = 0; i < n; i++) {
string str;
cin >> str;
for (int j = 0; j < n; j++) {
board[i][j] = str[j] - '0';
}
}
priority_queue<RoomInfo> pq;
pq.push({ start.first,start.second,0 });
found[start.first][start.second] = true;
int ans = 0;
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
if (curr.row == target.first && curr.col == target.second) {
ans = curr.breakCnt;
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 >= n) continue;
if (found[nextRow][nextCol]) continue;
if (board[nextRow][nextCol] == 0)
pq.push({ nextRow,nextCol,curr.breakCnt + 1 });
else
pq.push({ nextRow,nextCol,curr.breakCnt });
found[nextRow][nextCol] = true;
}
}
cout << ans;
}