백준 17086 c++

magicdrill·2024년 4월 19일
0

백준 문제풀이

목록 보기
330/654

백준 17086 c++

문제를 잘못 읽었다. 아기상어에서 다른 아기상어까지의 거리가 아니라, 아무 빈칸에서 악어까지의 거리 중 최대거리를 구하는 문제였다... DP로도 풀수 있을거 같다?

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

using namespace std;

//브루트 포스 카테고리긴 한데....BFS로...어차피 브루트 포스 + BFS임

vector <vector<int>> space;
vector <vector<bool>> visited;
vector <pair<int, int>> baby_shark;
int N, M;

void reinit_visited()
{
	int i, j;

	for (i = 0; i < N; i++)
	{
		for (j = 0; j < M; j++)
		{
			visited[i][j] = false;
		}
	}

	return;
}

void input_space()
{
	int i, j;

	cin >> N >> M;
	space.resize(N, vector<int>(M, 0));
	visited.resize(N, vector<bool>(M, false));
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < M; j++)
		{
			cin >> space[i][j];
			if (space[i][j] == 1)
			{
				baby_shark.push_back({ j, i });//x,y좌표
			}
		}
	}

	return;
}

int BFS(int start_x, int start_y)
{
	vector<pair<int, int>> direction{ {1, 0},{1, 1},{0, 1},{-1, 1},{-1, 0}, {-1, -1},{0, -1},{1, -1} };
	queue<pair<int, int>> q;
	int current_x, current_y, next_x, next_y;
	int i, j, q_size, d_size = direction.size(), count = 0;

	q.push({ start_x, start_y });
	visited[start_y][start_x] = true;
	while (!q.empty())
	{
		q_size = q.size();
		for (i = 0; i < q_size; i++)
		{
			current_x = q.front().first;
			current_y = q.front().second;
			q.pop();
			for (j = 0; j < d_size; j++)
			{
				next_x = current_x + direction[j].first;
				next_y = current_y + direction[j].second;
				if ((next_x >= 0 && next_x < M) && (next_y >= 0 && next_y < N) && (visited[next_y][next_x] == false))
				{
					if (space[next_y][next_x] == 1)
					{
						return count + 1;
					}
					else
					{
						visited[next_y][next_x] = true;
						q.push({ next_x, next_y });
					}
				}
			}
		}
		count++;
	}
}

void find_answer()
{
	int i, j, max = 0, temp;

	for (i = 0; i <N; i++)
	{
		for (j = 0; j < M; j++)
		{
			if (space[i][j] == 1)
			{
				continue;
			}
			temp = BFS(j, i);//x, y좌표
			if (temp > max)
			{
				max = temp;
			}
			reinit_visited();
		}
	}
	cout << max << "\n";

	return;
}

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

	input_space();
	find_answer();

	return 0;
}

0개의 댓글