백준 21736 c++

magicdrill·2024년 3월 20일

백준 문제풀이

목록 보기
177/675

백준 21736 c++

오랜만에 BFS를 사용한 문제를 풀었다.
처음에는 DFS와 BFS사이에서 고민을 했는데 일단은 그냥 풀어보기로 했다.
DFS로 풀어보신 분을 봤는데 시간은 큰 차이 없는거 같고 메모리 사용량은 BFS가 더 좋았다. DFS로도 풀어보겠다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

vector<vector<char>> map;
vector<vector<bool>> visited;
vector<vector<int>> direction{ {1, 0},{0, 1},{-1, 0},{0, -1} };
int doyeon_x, doyeon_y;
int N, M;

void input_map()
{
	int i, j;

	cin >> N >> M;
	map.resize(N, vector<char>(M));
	visited.resize(N, vector<bool>(M, false));
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < M; j++)
		{
			cin >> map[i][j];
			if (map[i][j] == 'I')
			{
				doyeon_x = j;
				doyeon_y = i;
			}
		}
	}
	//for (i = 0; i < N; i++)
	//{
	//	for (j = 0; j < M; j++)
	//	{
	//		cout << map[i][j] << " ";
	//	}
	//	cout << "\n";
	//}

	return;
}

int BFS(int start_x, int start_y)
{
	int count = 0, i, direct = direction.size();
	int current_x, current_y; 
	int next_x, next_y;
	queue <pair<int, int>> q;

	q.push({ start_x, start_y });
	visited[start_y][start_x] = true;
	while (!q.empty())
	{
		current_x = q.front().first;
		current_y = q.front().second;
		q.pop();
		for (i = 0; i < direct; i++)
		{
			next_x = current_x + direction[i][0];
			next_y = current_y + direction[i][1];
			if ((next_x >= 0 && next_x < M) && (next_y >= 0 && next_y < N)
				&& visited[next_y][next_x] == false && map[next_y][next_x] != 'X')
			{
				if (map[next_y][next_x] == 'O')
				{
					visited[next_y][next_x] = true;
					q.push({ next_x, next_y });
				}
				else //(map[next_y][next_x] == 'P')
				{
					visited[next_y][next_x] = true;
					q.push({ next_x, next_y });
					count++;
				}
			}
		}
	}

	return count;
}

void find_answer()
{
	//DFS? BFS? 최단거리 아니니까 DFS아닌가?
	//BFS로 하면 필요 없는 길을 너무 다 가보는거 아닌가?
	//큐가 거의 36만개가 생기는데...
	//일단 BFS로 해보자
	//cout << BFS(doyeon_x, doyeon_y) << "\n";
	int answer;

	answer = BFS(doyeon_x, doyeon_y);
	if (answer == 0)
	{
		cout << "TT" << "\n";
	}
	else
	{
		cout << answer << "\n";
	}

	return;
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	input_map();
	find_answer();

	return 0;
}

0개의 댓글