백준 2234 성곽 ❌

CJB_ny·2023년 3월 10일
0

백준

목록 보기
100/104
post-thumbnail

성곽

내제출


후기

Connected Coponent 가 생각이 남.
또한 DFS랑 비트연산자를 통해서 뭐 for문을 돌려서

1번 2번 출력은 우째우째 구했음.

근데 3번 벽을 뚫어서 가장넓은 방 넓이를 구하는 부분에서 cp라는 변수로 cp가 2이상일때 다시 DFS를 한번 더 돌려서 구할려고 했으나 실패..

추가적으로 해당문제 입력이 배운점인거같다.
비트 연산을 할 수 있도록 벽을 2진수로 나타내서 어디가 뚫려있는지 나타내는 부분을 공부함.

강의랑 전체 로직은 비슷했다. cp를 사용한거랑 id를 사용한 부분. 다만 벽 허물었을 때가 다름.

추가로, 로직 자체가 서 -> 북 -> 동 -> 남 이기때문에 dy, dx 방향도 신경써주어야했다.

분석

  • Connected Component(DFS)
  • BitMasking

cpp

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define endl "\n"
#define ll long long
#define MAX 54

int col, row, a[MAX][MAX], visited[MAX][MAX], id = 0;
int dy[4] = { 0, -1, 0, 1 }, dx[4] = { -1, 0, 1, 0 };
int compSize[2504], mx = -1, big = -1;

bool Cango(int y, int x)
{
	if (y < 0 || x < 0 || y >= row || x >= col) return false;
	return true;
}

int DFS(int y, int x, int c)
{
	if (visited[y][x]) return 0;

	visited[y][x] = c;
	int ret = 1;
	for (int i = 0; i < 4; ++i)
	{
		if ((a[y][x] & (1 << i)) == 0)
		{
			int ny = y + dy[i];
			int nx = x + dx[i];
			ret += DFS(ny, nx, c);
		}
	}
	return ret;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	cin >> col >> row;
	for (int y = 0; y < row; ++y)
		for (int x = 0; x < col; ++x)
			cin >> a[y][x];
	
	// 1번, 2번 구하는 부분
	for (int y = 0; y < row; ++y)
	{
		for (int x = 0; x < col; ++x)
		{
			if (!visited[y][x])
			{
				++id; // CC
				compSize[id] = DFS(y, x, id);
				mx = max(mx, compSize[id]);
			}
		}
	}

	// 3번 : 벽허무는 부분
	for (int y = 0; y < row; ++y)
	{
		for (int x = 0; x < col; ++x)
		{
			// OverFlow Check
			if (y + 1 < row)
			{
				int a = visited[y + 1][x];
				int b = visited[y][x];
				if (a != b)
				{
					big = max(big, compSize[a] + compSize[b]);
				}
			}
			if (x + 1 < col)
			{
				int a = visited[y][x + 1];
				int b = visited[y][x];
				if (a != b)
				{
					big = max(big, compSize[a] + compSize[b]);
				}
			}
		}
	}

	cout << id << endl;
	cout << mx << endl;
	cout << big << endl;

	return 0;
}
profile
https://cjbworld.tistory.com/ <- 이사중

0개의 댓글