본문 바로가기
이론/코딩테스트

[백준] 2468번 안전 영역 (BFS)

by 퇴근후개발 2022. 7. 31.
반응형

-문제

틀렸습니다 나왔던 이유 : 특정 케이스 확인 필요

초기 케이스(?) 확인하자

1 1

1 1

해당 케이스는 1이 나와야한다.

 

 

-코드

#include<stdio.h>
#include<queue>
using namespace std;

int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1};
int main()
{
	queue<pair<int, int> > q;
	int n, cnt = 0, min = 100, max = 1, res = 0;
	scanf("%d", &n);
	int map[100][100], ch[100][100];
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			scanf("%d", &map[i][j]);
			if (map[i][j] > max) max = map[i][j];
			if (map[i][j] < min) min = map[i][j];
		}
	}

	if (max == min)
	{
		res = 1; 
		printf("%d", res);
		return 0;
	}

	while (min < max)
	{
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				ch[i][j] = 0;
			}
		}

		cnt = 0;
		for (int x = 0; x < n; x++)
		{
			for (int y = 0; y < n; y++)
			{
				if (ch[x][y] == 0 && map[x][y] > min)
				{
					q.push({ x,y });
					ch[x][y] = 1;
					while (!q.empty())
					{
						pair<int, int> tmp = q.front();
						q.pop();
						for (int j = 0; j < 4; j++)
						{
							int xx = tmp.first + dx[j];
							int yy = tmp.second + dy[j];
							if (xx < 0 || yy < 0 || xx >= n || yy >= n) continue;
							if (map[xx][yy] > min && ch[xx][yy] == 0)
							{
								ch[xx][yy] = 1;
								q.push({ xx,yy });
							}
						}
					}
					cnt++;
				}
			}
		}
		if (res < cnt) res = cnt;
		min++;
	}
	printf("%d", res);
	return 0;
}
반응형