KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • programmers
  • 정렬
  • 문자열
  • 다이나믹 프로그래밍
  • 수학
  • C++
  • recursion
  • C
  • LeetCode
  • 백준
  • 그래프
  • js
  • Level1
  • 제코베 JS 100제
  • Level 1
  • Level 0
  • codeup
  • Level 2
  • string
  • tree

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/백준

백준 / 그래프 / 11724번 / 연결 요소의 개수 / JS

2023. 12. 24. 21:06

< 문제 바로가기 >

 

11724번: 연결 요소의 개수

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어

www.acmicpc.net

 

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : '../input.txt';
// const filePath = process.platform === 'linux' ? '/dev/stdin' : 'BOJ/input.txt';
const input = fs.readFileSync(filePath).toString().trim().split('\n');

const [N, M] = input.shift().split(' ').map(Number);
const edgeList = input.map(row => row.split(' ').map(Number));

/** 인접 행렬 */
const adjList = Array.from({ length: N + 1 }, () => []);
/** 방문 처리 배열 */
const visited = Array.from({ length: N + 1 }, () => false);
/** 연결된 개수 */
let connectedCount = 0;

const solution = () => {
  init();
  solve();

  console.log(connectedCount);
};

/**
 * 인접행렬을 초기화하는 함수
 */
const init = () => {
  for(const [start, end] of edgeList) {
    adjList[start].push(end);
    adjList[end].push(start);
  }
}

const solve = () => {
  for(let i=1; i<=N; i++) {
    // 만약 미방문한 노드라면,
    if(visited[i] === false) {
      // dfs를 수행하고,
      dfs(i);
      // dfs를 마치면 연결된 개수를 하나 더해준다.
      connectedCount++;
    }
  }
}

/**
 * dfs를 이용해서 연결된 모든 노드를 방문처리하는 함수
 * 
 * @param {number} start 현재 노드
 */
const dfs = (start) => {
  visited[start] = true;

  for(const next of adjList[start]) {
    if(visited[next] === true) {
      continue;
    }

    dfs(next);
  }
}

solution();
저작자표시

'PS > 백준' 카테고리의 다른 글

백준 / 그래프 / 2667번 / 단지번호붙이기 / JS  (0) 2023.12.25
백준 / 그래프 / 7562번 / 나이트의 이동 / JS  (0) 2023.12.24
백준 / 그래프 / 숨바꼭질 4 / JS  (0) 2023.12.21
백준 / 그래프 / 1697번 / 숨바꼭질 / JS  (0) 2023.12.19
    'PS/백준' 카테고리의 다른 글
    • 백준 / 그래프 / 2667번 / 단지번호붙이기 / JS
    • 백준 / 그래프 / 7562번 / 나이트의 이동 / JS
    • 백준 / 그래프 / 숨바꼭질 4 / JS
    • 백준 / 그래프 / 1697번 / 숨바꼭질 / JS
    KimMinJun
    KimMinJun

    티스토리툴바