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
- 스나이퍼팩토리
- 수코딩
- sucoding
- tanstack query
- 리액트프로젝트
- 프론트엔드
- React
- 공식문서
- 개발
- Server State
- 프론트엔드 개발
- 상태 관리 라이브러리
- 웅진씽크빅
- 유데미
- STATE
- React Query
- frontend
- 프로젝트캠프
- TypeScript
Archives
- Today
- Total
yunicornlab
백준 1707번 이분 그래프 JavaScript 풀이 [BFS] 본문
반응형
백준 1707번 이분 그래프 문제를 자바스크립트로 BFS 알고리즘을 이용해서 풀어보았다.
https://www.acmicpc.net/problem/1707
while 문으로 BFS 돌리기 전에 모든 노드를 순회하는 for문을 추가해줬어야 했다.
이것 때문에 한참 헤맸다..
/*
'/dev/stdin'
*/
let path = 'input.txt';
let fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
let testCase = Number(input[0]);
let t = 1;
class Queue {
constructor() {
this.items = {};
this.head = 0;
this.tail = 0;
}
enqueue(element) {
this.items[this.tail] = element;
this.tail++;
}
dequeue() {
const element = this.items[this.head];
delete this.items[this.head];
this.head++;
return element;
}
getLength() {
return this.tail - this.head;
}
}
while (testCase--) {
let [v, e] = input[t].split(' ').map(Number);
let graph = new Array(v+1).fill().map(_ => []);
for (let i=1; i<=e; i++) {
let [start, end] = input[t + i].split(' ').map(Number);
graph[start].push(end);
graph[end].push(start);
}
// 미방문 0, 검정색 : 1, 하얀색 : -1
let visited = new Array(v+1).fill(0);
// 모든 노드 순회
for (let node=1; node<=v; node++) {
// 방문 안한 노드이면
if (visited[node] == 0) {
queue = new Queue();
queue.enqueue(node)
visited[node] = 1;
// BFS로 색상값을 visited에 삽입
while (queue.getLength() != 0) {
let x = queue.dequeue();
for (let y of graph[x]) {
if (visited[y] == 0) {
visited[y] = visited[x] * (-1);
queue.enqueue(y);
}
}
}
}
}
// 이분 그래프인지 visited를 순회하면서 확인
let result = "YES";
for (let x=1; x<=v; x++) {
for (let y of graph[x]) {
if (visited[x] == visited[y]) {
result = "NO";
break;
}
}
}
console.log(result)
// 다음 테스트 케이스로 이동
t += e + 1;
}
반응형
'Coding Test > Practice' 카테고리의 다른 글
백준 18405번 경쟁적 전염 JavaScript 풀이 [BFS] (0) | 2024.07.26 |
---|---|
백준 14395번 4연산 JavaScript 풀이 [BFS] (0) | 2024.07.26 |
백준 7562번 나이트의 이동 풀이 [BFS] (0) | 2024.07.26 |
백준 21921번 블로그 JavaScript 풀이 [투포인터] (1) | 2024.07.22 |
백준 11441번 합 구하기 JavaScript 풀이 [누적합] (0) | 2024.07.21 |