티스토리 뷰

알고리즘 풀이/BFS

BOJ : 3055 탈출

jonyo 2020. 8. 5. 23:07


[BOJ 3055(G5) 리뷰]

이전에 풀었던 불! 문제와 비슷한 유형이다. 그때 썼던 코드를 거의 그대로 가져다 썼다.

먼저 물에대해 BFS를 수행하고 고슴도치에 대해 BFS를 수행하면 된다.

 


#include <iostream>
#include <algorithm>
#include <list>
#include <string>
#include <vector>
#include <stack>
#include <utility>
#include <queue>
#include <deque>
using namespace std;

#define X first
#define Y second
string board[1002];
int dist[1002][1002];
int dist2[1002][1002];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

int main(void)
{
	cin.tie(0);
	ios::sync_with_stdio(0);

	int n, m;
	cin >> n >> m;
	int ret = 0;
	queue <pair<int, int>> Q; 
	queue <pair<int, int>> Q2; 
	pair <int, int> dest;
	for (int i = 0; i < n; i++)
	{
		cin >> board[i];
	}

	for (int i = 0; i < n; i++)
	{
		fill(dist[i], dist[i] + m, -1);
		fill(dist2[i], dist2[i] + m, -1);
	}

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (board[i][j] == 'S')
			{
				Q.push({ i,j });
				dist[i][j] = 0;
			}
			if (board[i][j] == '*')
			{
				Q2.push({ i,j });
				dist2[i][j] = 0;
			}
			if (board[i][j] == 'D')
			{
				dest = make_pair(i, j);
			}
		}
	}

	while (!Q2.empty())
	{
		auto cur = Q2.front();
		Q2.pop();
		for (int dir = 0; dir < 4; dir++)
		{
			int nx = cur.X + dx[dir];
			int ny = cur.Y + dy[dir];
			if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
			if (dist2[nx][ny] >= 0 || board[nx][ny] == 'X') continue;
			if (board[nx][ny] == 'D') continue;
			dist2[nx][ny] = dist2[cur.X][cur.Y] + 1;
			Q2.push({ nx,ny });
		}
	}



	while (!Q.empty()) 
	{
		auto cur = Q.front();
		if (board[cur.X][cur.Y] == 'D') break;
		Q.pop();
		for (int dir = 0; dir < 4; dir++)
		{
			int nx = cur.X + dx[dir];
			int ny = cur.Y + dy[dir];
			if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
			if (dist[nx][ny] >= 0 || board[nx][ny] == 'X') continue;
			if (dist2[nx][ny] != -1 && dist[cur.X][cur.Y] + 1 >= dist2[nx][ny]) continue;
			dist[nx][ny] = dist[cur.X][cur.Y] + 1;
			Q.push({ nx,ny });
		}
	}

	if(dist[dest.X][dest.Y]!=-1) cout << dist[dest.X][dest.Y];
	else cout << "KAKTUS";
	
}

 

 

'알고리즘 풀이 > BFS' 카테고리의 다른 글

BOJ : 2589 보물섬  (0) 2020.08.05
BOJ 1389 : 케빈 베이컨의 6단계 법칙  (0) 2020.08.05
BOJ : 13913 숨바꼭질 4  (0) 2020.08.05
BOJ : 6593 상범 빌딩  (0) 2020.08.05
BOJ 5014 : 스타트링크  (0) 2020.08.04
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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 29 30 31
글 보관함