관리 메뉴

KorSA

GALLERY 본문

Algorithm/Graph - DFS

GALLERY

Praiv. 2020. 8. 24. 09:40
320x100
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool **gAdj;

int galleryNum = 0, hallwayNum = 0;

vector<bool> visited;
const int UNWATCHED = 0;
const int WATCHED = 1;
const int INSTALLED = 2;

int installCount = 0;

int dfsForInstall(int here);
int installCamera();

int main()
{
	int caseNum = 0;
	cin >> caseNum;
	cin.ignore();

	for (int cIter = 0; cIter < caseNum; cIter++)
	{
#pragma region READ INPUT

		cin >> galleryNum >> hallwayNum;

		// Allocate adjacent
		gAdj = new bool*[galleryNum];
		for (int i = 0; i < galleryNum; i++)
			gAdj[i] = new bool[galleryNum] {false, };

		int hFrom = -1, hTo = -1;
		for (int hIter = 0; hIter < hallwayNum; hIter++)
		{
			cin >> hFrom >> hTo;
			gAdj[hFrom][hTo] = true;
		}
#pragma endregion

		int installCnt = installCamera();

#pragma region OUTPUT
		cout << installCnt << endl;
#pragma endregion

#pragma region DISPOSE
		for (int i = 0; i < galleryNum; i++)
			delete[] gAdj[i];
		delete[] gAdj;
#pragma endregion
	}
}

int dfsForInstall(int here)
{
	visited[here] = true;

	int children[3] = { 0, 0, 0 };

	for (int there = 0; there < galleryNum; there++)
	{
		if (gAdj[here][there] == false) continue;
		if (visited[there]) continue;

		++children[dfsForInstall(there)];
	}

	if (children[UNWATCHED])
	{
		installCount++;
		return INSTALLED;
	}

	if (children[INSTALLED])
		return WATCHED;

	return UNWATCHED;
}

int installCamera()
{
	installCount = 0;
	visited = vector<bool>(galleryNum, false);

	for (int u = 0; u < galleryNum; u++)
	{
		if (visited[u] == false && dfsForInstall(u) == UNWATCHED)
		{
			++installCount;
		}
	}

	return installCount;
}
728x90
728x90

'Algorithm > Graph - DFS' 카테고리의 다른 글

DICTIONARY  (0) 2020.08.24
Comments