티스토리 뷰
반응형
백준 5427번 불
https://www.acmicpc.net/problem/5427
5427번: 불
상근이는 빈 공간과 벽으로 이루어진 건물에 갇혀있다. 건물의 일부에는 불이 났고, 상근이는 출구를 향해 뛰고 있다. 매 초마다, 불은 동서남북 방향으로 인접한 빈 공간으로 퍼져나간다. 벽에
www.acmicpc.net




정답 코드
#include<iostream>
#include<queue>
using namespace std;
char arr[1001][1001];
int time1[1001][1001];
int time2[1001][1001];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
void bfs() {
queue<pair<int, int>>q1;
queue<pair<int, int>>q2;
int w, h;
cin >> w >> h;
for (int i = 0; i < 1001; i++) {
for (int j = 0; j < 1001; j++) {
time1[i][j] = -1;
time2[i][j] = -1;
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> arr[i][j];
if (arr[i][j] == '*') {
time1[i][j] = 0;
q1.push({ i,j });
}
else if (arr[i][j] == '@') {
time2[i][j] = 0;
q2.push({ i,j });
}
}
}
while (!q1.empty()) { // 불
pair<int, int>cur = q1.front();
q1.pop();
for (int dir = 0; dir < 4; dir++) {
int mx = cur.first + dx[dir];
int my = cur.second + dy[dir];
if (mx < 0 || my < 0 || mx >= h || my >= w)
continue;
if (arr[mx][my] == '#' || time1[mx][my] >= 0)
continue;
time1[mx][my] = time1[cur.first][cur.second] + 1;
q1.push({ mx,my });
}
}
while (!q2.empty()) { //상근이
pair<int, int>cur = q2.front();
q2.pop();
for (int dir = 0; dir < 4; dir++) {
int mx = cur.first + dx[dir];
int my = cur.second + dy[dir];
if (mx < 0 || my < 0 || mx >= h || my >= w) {
cout << time2[cur.first][cur.second] + 1;
return;
}
if (arr[mx][my] == '#' || time2[mx][my] >= 0)
continue;
if (time1[mx][my] != -1 && time1[mx][my] <= time2[cur.first][cur.second] + 1)
continue;
time2[mx][my] = time2[cur.first][cur.second] + 1;
q2.push({ mx,my });
}
}
cout << "IMPOSSIBLE";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int test;
cin >> test;
for (int x = 0; x < test; x++) {
bfs();
cout << '\n';
}
}
문제 풀이
불이 확산되는 것과 상근이가 이동하는 것을 분리해서 생각했습니다. 그리고 불이 먼저 확산되는 것을 bfs로 만든 후 상근이가 이동할 때 이것을 고려하게 만들었습니다. 그래서 time배열을 2개를 만들었습니다. 불이 확산되는 부분은 배열의 범위와 이미 방문한 곳, 벽을 고려하였습니다. 상근이가 움직이는 것은 벽인 곳, 이미 방문한 곳, 벽은 아니지만 불이 확산될 수 있는 곳을 고려하였고 배열의 범위를 벗어나면 그때의 시간을 출력하였습니다.
반응형
'Algorithm > BOJ' 카테고리의 다른 글
백준 5597번 C++ (0) | 2023.08.20 |
---|---|
백준 5522번 C++ (2) | 2023.08.20 |
백준 5347번 C++ (0) | 2023.08.20 |
백준 5339번 C++ (0) | 2023.08.20 |
백준 5338번 C++ (0) | 2023.08.20 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- c++ string
- 유클리드 호제법
- js
- Do it!
- C++
- 알고리즘
- 알고리즘 공부
- 이분 매칭
- 에라토스테네스의 체
- java
- 자바
- 자료구조
- HTML5
- html
- BFS
- 백준 풀이
- 유니온 파인드
- 카운팅 정렬
- DP
- CSS
- 세그먼트 트리
- C++ Stack
- 자바스크립트
- 투 포인터
- 반복문
- 스프링 부트 crud 게시판 구현
- 백준
- 우선순위 큐
- 스택
- DFS
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함