사이클이 없는 유향 그래프를 의미한다.
특정 그래프가 DAG인지 판별하기 위해선 다음 방법들을 사용할 수 있다.
노드는 다음 3가지 상태를 가진다.
enum Color { WHITE, // never visited GRAY, // there are white neighber BLACK // there are no white neighber };
DFS를 진행하며 각 노드들의 현재 상태를 call stack에서 이용하고 이를 갱신하다.
현재 상태에서 현재 노드의 상태에 따라서 다음과 같이 진행한다.
따라서 DFS로 탐색할 때 현재 구간에서 이웃 노드들에 사이클이 있는지 여부를 판별하며 DAG인지를 판단한다.
이를 구현하면 다음과 같다.
vector<Color> colors; vector<vector<int>> graph; // 모든 노드를 WHITE로 초기화 bool isAcyclic(int from) { if (colors[from] == Color::BLACK) return true; if (colors[from] == Color::GRAY) return false; colors[from] = Color::GRAY; for (const int &next : graph[from]) { bool hasCycle = !isAcyclic(next); if (hasCycle) return false; } colors[from] = Color::BLACK; return true; }
위상 정렬을 수행하며 사이클이 있는 경우를 판별할 수 있다.
There was an error while loading. Please reload this page.