Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 프로그래머스
- Python
- 면접질문
- 쿠쉬쿠쉬
- 고득점Kit
- C
- 문제풀이
- Lv.2
- hash
- 코딩테스트준비
- 그래프
- 2색칠하기
- LV.3
- 해시
- Java
- 알고리즘
- OS
- BruteForceSearch
- Lv.1
- 코테준비
- C++
- 운영체제
- Algorithm
- 코딩테스트
- BFS
- 이분그래프판별
- 동적계획법
- 파이썬
- 단지번호붙이기
Archives
- Today
- Total
쿠쿠의기록
19. 2색칠하기(BFS) 본문
문제
2색 칠하기란, 다음 두 조건을 만족하면서 그래프의 정점을 모두 색칠할 수 있는지 묻는 문제이다. 2개의 색이 존재한다. 인접한 두 정점은 색깔이 다르다. 그래프가 주어질 때, 2색 칠하기가 가능한지 출력하는 프로그램을 작성하시오. 예를 들어, 아래의 그래프는 2색 칠하기가 가능한 그래프이며, 정점을 색칠한 결과는 다음과 같다.

입력
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. ( 1 ≤ N ≤ 10,000, 1 ≤ M ≤ 100,000 ) 둘째 줄부터 간선의 정보가 주어진다. 각 줄은 두 개의 숫자 a, b로 이루어져 있으며, 이는 정점 a와 정점 b가 연결되어 있다는 의미이다.(0 ≤ a, b ≤ N-1)
출력
주어진 그래프에 대하여 2색 칠하기를 할 수 있으면 YES, 할 수 없으면 NO를 출력한다.
예제 입력
9 10
0 1
0 2
0 3
1 5
2 5
3 4
5 6
5 8
6 7
7 8
예제 출력
YES
예제 입력
9 11
0 1
0 2
0 3
1 5
2 5
3 4
4 5
5 6
5 8
6 7
7 8
예제 출력
NO
#include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 10010;
int n,m;
vector <int> myGraph[MAX];
int check[MAX] ={0,};
int color[MAX] ={0,};
queue <int> q;
int flag = 0;
void BFS(){
if(q.empty()) return;
int current = q.front(); //0
int node_color = color[current]; //1
q.pop();
check[current] = 1; //0
for(int i=0;i<myGraph[current].size();i++){
if(color[myGraph[current][i]] == node_color){
//printf("%d ",myGraph[current][i]);
flag =-1;
return;
}
//printf("%d ",myGraph[current][i]);
if(check[myGraph[current][i]]==0){
q.push(myGraph[current][i]);
check[myGraph[current][i]]=1;
color[myGraph[current][i]]=node_color*-1;
}
}
if(!q.empty()){
BFS();
}
}
int main() {
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++){
int a,b;
scanf("%d %d",&a,&b);
myGraph[a].push_back(b);
myGraph[b].push_back(a);
}
q.push(0);
color[0] = 1;
BFS();
if(flag == 0){
printf("YES");
}else{
printf("NO");
}
return 0;
}
https://github.com/kuminkyu/SoloStudy/blob/master/AlgorithmTest/level19/2%EC%83%89%EC%B9%A0%ED%95%98%EA%B8%B0(BFS).c%2B%2B
'알고리즘 > L19 BFS,DFS' 카테고리의 다른 글
19. 단지 번호 붙이기 (0) | 2023.07.11 |
---|---|
19. 미로 찾기 (0) | 2023.07.05 |
19. 웜 바이러스 (0) | 2023.07.04 |
19. 이분 그래프 판별 (0) | 2023.06.28 |
19. 깊이우선탐색과 너비우선탐색 (0) | 2023.06.26 |