[BOJ/C++] 4179 ๋ถˆ! : BFS

Hanbiยท2024๋…„ 6์›” 12์ผ
0

Problem Solving

๋ชฉ๋ก ๋ณด๊ธฐ
119/128
post-thumbnail
post-custom-banner

๋ฌธ์ œ

https://www.acmicpc.net/problem/4179

ํ’€์ด

BFS ์‘์šฉ ๋ฌธ์ œ๋‹ค. ์˜ˆ์ „์— ์ด์™€ ๋น„์Šทํ•œ ๋ฌธ์ œ๋ฅผ ํ‘ผ ์ ์ด ์žˆ๋Š”๋ฐ ์ง€๊ธˆ๋ณด๋‹ˆ ์ฝ”๋“œ ๋กœ์ง์ด ๋น„ํšจ์œจ์ ์ธ ๊ฒƒ ๊ฐ™์•„์„œ ๋” ํšจ์œจ์ ์ธ ๋ฐฉ์‹์œผ๋กœ ํ’€์ดํ–ˆ๋‹ค.

  1. ๋ถˆ๋กœ bfs ์ง„ํ–‰
    (์ฒ˜์Œ์— ๋ถˆ์˜ map์„ INF๋กœ ์ดˆ๊ธฐํ™”ํ•˜๊ณ , ๊ธฐ์กด ๊ฐ’๋ณด๋‹ค ๊ฐ’์ด ์ž‘์œผ๋ฉด ๊ฐฑ์‹ ํ•˜๊ณ  ํ์— push!)
  2. ์ง€ํ›ˆ์ด bfs ์ง„ํ–‰
    (๋ถˆ map๋ณด๋‹ค ๊ฐ’์ด ์ž‘์€ ๊ฒฝ์šฐ์—๋งŒ ๊ณ„์†ํ•ด์„œ bfs ์ง„ํ–‰)

๐ŸŒŸ์ตœ๋Œ“๊ฐ’ ์ดˆ๊ธฐํ™”ํ•  ๋•Œ, limit.h ํ—ค๋” INT_MAX๊ฐ’ ์ด์šฉ
๐ŸŒŸํ๋ฅผ ๋ฌด์กฐ๊ฑด pair ํ˜•ํƒœ๋กœ ํ•  ๊ฒŒ ์•„๋‹ˆ๋ผ, ๊ตฌ์กฐ์ฒด ๋งŒ๋“ค์–ด์„œ ๊ตฌ์กฐ์ฒด ํ ์„ ์–ธํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋” ๊น”๋”ํ•จ

์ฝ”๋“œ

#include <iostream>
#include <queue>
#include <limits.h>

using namespace std;

int R, C;
int fire[1001][1001];
char map[1001][1001];
bool visited[1001][1001];
queue<pair<int, int>> fire_q;
int mark = 0;

int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };

struct moves {
	int x;
	int y;
	int cnt;
};

void f_bfs() {
	while (!fire_q.empty()) {
		int xx = fire_q.front().first;
		int yy = fire_q.front().second;

		fire_q.pop();
		for (int i = 0; i < 4; i++) {
			int nx = xx + dx[i];
			int ny = yy + dy[i];

			if (nx < 0 || nx >= R || ny < 0 || ny >= C || map[nx][ny] == '#')	continue;
			if (fire[nx][ny] > fire[xx][yy] + 1) {
				fire[nx][ny] = fire[xx][yy] + 1;
				fire_q.push({ nx, ny });
			}
		}
	}
}

void j_bfs(int x, int y) {
	visited[x][y] = true;

	queue<moves> q;
	q.push({ x, y });
	
	while (!q.empty()) {
		int xx = q.front().x;
		int yy = q.front().y;
		int cnt = q.front().cnt;

		q.pop();

		if (xx == 0 || xx == R - 1 || yy == 0 || yy == C - 1) {
			cout << cnt + 1;
			mark = 1;
			return;
		}

		for (int i = 0; i < 4; i++) {
			int nx = xx + dx[i];
			int ny = yy + dy[i];

			if (nx < 0 || nx >= R || ny < 0 || ny >= C || map[nx][ny] == '#' || visited[nx][ny])	continue;
			if (fire[nx][ny] > cnt + 1) {
				visited[nx][ny] = true;
				q.push({ nx, ny, cnt+1 });
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int sx = 0, sy = 0;
		
	cin >> R >> C;
	for (int i = 0; i < R; i++) {
		for (int j = 0; j < C; j++) {
			fire[i][j] =INT_MAX;
			cin >> map[i][j];
			if (map[i][j] == 'J') {
				sx = i;
				sy = j;
			}
			else if (map[i][j] == 'F') {
				fire_q.push({ i, j });
				fire[i][j] = 0;
			}
		}
	}

	f_bfs();
	j_bfs(sx, sy);

	if(mark == 0)
		cout << "IMPOSSIBLE";

	return 0;
}
profile
๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€