487 words
2 minutes
[BOJ] 시루의 백화점 구경
TimeLimit | MemoryLimit | Condition | TAG |
---|---|---|---|
2s | 1024MB | (1 ≤ N, M ≤ 2000, 0 ≤ K ≤ 4000) | BFS |
이 문제도 전형적인 BFS 문제이구요. 조금 BFS 연습하고 싶을 때 와서 풀어보면 좋을 것 같아요. 그냥 기본 BFS로 푸는거라서… 그런데 저는 조금 이상하게 푼 ㅓㄱ 같기두 하고요…
뭔가 애매하고 들어간 느낌? 하튼 재밌었습니다… 낼 학교 준비해야징..
풀이 영상
정답 코드
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
using ll = long long;
int inf = 1000000000;
int n, m, k;
int visited[2001][2001];
int board[2001][2001];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, -1, 1};
void init(vector<pair<int, int>>& hs){
queue<pair<int, pair<int,int>>> q;
for(pair<int, int> pos : hs) {
q.push({0, pos});
visited[pos.first][pos.second] = -1;
}
while(!q.empty()){
auto [cost, p] = q.front(); q.pop();
visited[p.first][p.second] = -1;
// cout << "start: " << p.first << " " << p.second << "\n"; 이게 아닌가...?
for(int i = 0; i < 4; i++){
int nx = p.second + dx[i];
int ny = p.first + dy[i];
if(cost < k && 0 <= ny && ny < n && 0 <= nx && nx < m &&
visited[ny][nx] != -1){
// cout << ny << " " << nx << "\n";
visited[ny][nx] = -1;
q.push({cost+1, {ny, nx}});
}
}
}
// for(int i = 0; i < n; i++){
// for(int j = 0; j < m; j++){
// cout << visited[i][j] << " ";
// }
// cout << "\n";
// }
}
int solution(pair<int ,int> player){
priority_queue<pair<int, pair<int,int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> q;
q.push({0, player});
while(!q.empty()){
auto [cost, pos] = q.top(); q.pop();
if(board[pos.first][pos.second] == 2) return cost;
for(int i = 0; i < 4; i++){
int nx = pos.second + dx[i];
int ny = pos.first + dy[i];
if(0 <= ny && ny < n && 0 <= nx && nx < m && visited[ny][nx] > cost && board[ny][nx] != 1){
visited[ny][nx] = cost;
q.push({cost+1, {ny, nx}});
}
}
}
return -1;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n >> m >>k;
pair<int, int> player;
vector<pair<int, int>> hs;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> board[i][j];
switch(board[i][j]){
case 3:
hs.push_back({i, j});
break;
case 4:
player = {i, j};
case 1: // 벽 뒤에 있는 경우도 있을듯.
case 2:
break;
}
visited[i][j] = inf;
}
}
init(hs);
cout << solution(player);
return 0;
}
[BOJ] 시루의 백화점 구경
https://compy07.github.io/Blog/posts/boj/25307/