[C++, 백준/11724번] 연결 요소의 개수

2025. 3. 7. 20:06·코테/백준

 


☑️ [C++, 11724번] 연결 요소의 개수

1️⃣ 문제

https://www.acmicpc.net/problem/11724

2️⃣ 접근

크래프톤 정글에서 제공한 문제를 다시 풀고 있다. 블로그에도 Python으로 풀이한 내용을 올린 적이 있는데, 접근 방법이 다르지 않다.

 

 

[Python, 백준/11724번] 연결 요소의 개수

☑️ [Python, 백준/11724번] 연결 요소의 개수1️⃣ 문제https://www.acmicpc.net/problem/11724방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오 2️⃣ 접

taeyeokim.tistory.com

 

그동안 프로그래밍에 소홀해서 그런가 의사 코드를 작성하는 것보다 C++로 풀이하는 것이 어려웠다... 다시 열심히 해보자!

 

3️⃣ 코드

#include <iostream>
#include <vector>
using namespace std;

typedef vector<vector<int>> Graph;

Graph createGraph(int vertex_count, int edge_count) {
	Graph graph(vertex_count + 1);

	for (int i = 0; i < edge_count; ++i) {
		int from, to;
		cin >> from >> to;
		graph[from].push_back(to);
		graph[to].push_back(from);
	}
	return graph;
}

void visitDFS(const Graph& graph, int currentVertex, vector<bool>& visited) {
	visited[currentVertex] = true;

	for (int vertex_num : graph[currentVertex]) {
		if (!visited[vertex_num])
		{
			visitDFS(graph, vertex_num, visited);
		}
	}
}

int countConnectedVertex(const Graph& graph, int vertex_count) {
	vector<bool> isVisited(vertex_count + 1, false);
	int connectedVertexCount = 0;

	for (int vertex = 1; vertex <= vertex_count; ++vertex) {
		if (!isVisited[vertex]) {
			++connectedVertexCount;
			visitDFS(graph, vertex, isVisited);
		}
	}

	return connectedVertexCount;
}

int main() {
	int vertex_count, edge_count;
	cin >> vertex_count >> edge_count;

	Graph graph = createGraph(vertex_count, edge_count);
	int result = countConnectedVertex(graph, vertex_count);

	cout << result << endl;

	return 0;
}

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

[Python, 2156번] 포도주 시식  (1) 2024.10.22
[Python, 2252번] 줄 세우기  (4) 2024.10.09
[Python, 10844번] 쉬운 계단 수  (0) 2024.10.08
[Python, 백준/21606번] 아침 산책  (0) 2024.10.07
[Python, 백준/11725번] 트리의 부모 찾기  (1) 2024.09.24
'코테/백준' 카테고리의 다른 글
  • [Python, 2156번] 포도주 시식
  • [Python, 2252번] 줄 세우기
  • [Python, 10844번] 쉬운 계단 수
  • [Python, 백준/21606번] 아침 산책
태역
태역
  • 태역
    RYULAB
    태역
  • 전체
    오늘
    어제
    • 분류 전체보기 N
      • 언어
        • C
        • C++
        • C#
      • 엔진, 프레임워크
        • Unity
        • Unreal
        • Electron
      • 공부 N
        • 디자인 패턴
        • 수학
        • CS
        • Git
        • 알고리즘 N
        • 자료구조
      • 코테
        • 프로그래머스
        • 백준
      • 독서
        • Effective C#
        • CLR via C#
        • 뇌를 자극하는 윈도우즈 시스템 프로그래밍
        • 오브젝트
        • CSAPP
        • OSTEP
      • 프로젝트
        • Unity
      • 개발 일지
        • 퓨처리티
        • 골든타임
      • 활동
        • 게임잼 후기
        • 게임제작동아리 브릿지
        • 크래프톤 정글
        • 기타
      • 기타
  • 블로그 메뉴

    • 링크

    • 공지사항

      • 2024 04 17
    • 인기 글

    • 태그

      티스토리챌린지
      인프런 #인프런강의후기 #게임개발 #게임개발강의 #인강후기 #강의후기 #게임개발자 #인프런강의
      오블완
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.3
    태역
    [C++, 백준/11724번] 연결 요소의 개수
    상단으로

    티스토리툴바