본문 바로가기

Algorithm

백준 17086번 아기 상어 2

반응형
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<string.h>
using namespace std;

int N, M;
int arr[50][50];
bool visit[50][50];

struct Node {
	int y;
	int x;
	int count;
};
int dy[8] = {-1,-1,-1,0,0,1,1,1};
int dx[8] = {-1,0,1,-1,1,-1,0,1};

int main(void)
{
	cin >> N >> M;
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < M; j++)
		{
			cin >> arr[i][j];
		}
	}
	
	int maxa = 0;
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < M; j++)
		{
			if (!arr[i][j])
			{
				memset(visit, 0, sizeof(visit));
				visit[i][j] = true;

				queue<Node> que;
				que.push({ i,j,0 });
				int mina = 987654321;
				while (!que.empty())
				{
					int y = que.front().y;
					int x = que.front().x;
					int count = que.front().count;
					que.pop();

					if (arr[y][x])
					{
						if (mina > count)
						{
							mina = count;
						}
					}
					else
					{
						for (int k = 0; k < 8; k++)
						{
							int newy = y + dy[k];
							int newx = x + dx[k];

							if (newy >= 0 && newy < N && newx >= 0 && newx < M)
							{
								if (!visit[newy][newx])
								{
									visit[newy][newx] = true;
									que.push({ newy,newx,count + 1 });
								}
							}
						}
					}
					

				}
				if (maxa < mina)
				{
					maxa = mina;
				}
			}
		}
	}
	cout << maxa << endl;
}
반응형