#include<iostream>
#include<vector>
using namespace std;
//다음 정점이 색이 있는 정점일 경우 같은 색일 경우 false를 리턴하여 정답을 찾아낸다.
bool dfs(int node, int c, vector<int> &color, vector< vector<int> > &vertex) {
color[node] = c;
for (int i = 0; i < vertex[node].size(); i++) {
int next = vertex[node][i];
if (color[next] == 0) {
if (dfs(next, 3 - c,color,vertex) == false) {
return false;
}
}
else if (color[next] == color[node]) {
return false;
}
}
return true;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<int> temp;
vector<vector<int> > vertex;
for (int i = 0; i < n; i++) {
vertex.push_back(temp);
}
for (int i = 0; i < m; i++) {
int v1, v2;
cin >> v1 >> v2;
v1--; v2--;
vertex[v1].push_back(v2);
vertex[v2].push_back(v1);
}
vector<int> color;
for (int i = 0; i < n; i++) {
color.push_back(0);
}
bool ok = true;
// 방문하지 않은 모든 정점을 방문하도록 한다.
for (int i = 0; i < n; i++) {
if (color[i] == 0) {
if (dfs(i, 1,color, vertex) == false) {
ok = false;
}
}
}
if (ok) { cout << "YES" << '\n'; }
else cout << "NO" << '\n';
}
return 0;
}
C++ 알고리즘/7. 그래프 알고리즘
댓글