-
문제
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
How to Solve ?
문제의 제목처럼, 풀이의 본질은 "DFS"와 "BFS"를 올바르게 알고 있는가에 대해 물어 보는 것이다.
function DFS(V) {visited[V] = 1;for (let i = 0; i < M; i++) {if (!visited[i] && map[V][i] === 1) {dfsOut += " " + i;DFS(i);}}}function BFS(V) {visited[V] = 1;const queue = [V];while (queue.length) {const next = queue.shift();for (let i = 1; i <= N; i++) {if (map[next][i] === 1 && !visited[i]) {visited[i] = true;bfsOut += " " + i;queue.push(i);}}}}// 인접 행렬을 만들어 주기 위한 함수function setConnection(map, v1, v2) {map[v1][v2] = 1;map[v2][v1] = 1;}// 입력let [N, M, V] = [4, 5, 1];let visited = Array(N + 1).fill(0);const map = Array.from(new Array(N + 1), () => new Array(N + 1).fill(0));// 연결const lines = [[1, 2],[1, 3],[1, 4],[2, 4],[3, 4],];// 인접 행렬로 변경for (let i = 0; i < M; i++) {setConnection(map, lines[i][0], lines[i][1]);}// 실행let dfsOut = "" + V;DFS(V);visited = visited.fill(0);let bfsOut = "" + V;BFS(V);console.log(dfsOut);console.log(bfsOut);'PS > 백준' 카테고리의 다른 글
[ 백준 - 1406 ] 에디터 ( 스택 _ 자바스크립트 ) (0) 2021.06.06 [ 백준 _ 2178 ] 미로탐색 ( BFS - 자바스크립트 ) (0) 2021.06.04 [ 백준 _ 2667 ] 단지번호 붙이기 (DFS) (0) 2021.06.04 [ 백준_2293 ] 동전 1 ( DP, by using JavaScript ) (0) 2021.06.03 [백준_2437] 저울 ( by using Javascript ) (0) 2021.06.03