상위 150개 인터뷰쉬움

연결된 구성 요소 수

'연결된 구성 요소 수' 문제에 대한 자세한 가이드 및 Python 구현입니다.

문제 설명

쉬움

n개의 노드로 구성된 그래프가 있습니다. 정수 n과 edge[i] = [ai, bi]가 그래프의 ai와 bi 사이에 방향이 지정되지 않은 간선이 있음을 나타내는 배열 edge가 제공됩니다.

그래프의 연결된 구성 요소 수를 반환합니다.

countComponents(n: int, edges: List[List[int]]) -> int 함수를 작성하세요.

제약
  • 1 <= n <= 2000
  • 0 <= len(edges) <= 5000
  • edges[i].length == 2
  • 0 <= ai, bi < n

Example 1
Input
n = 5, edges = [[0,1],[1,2],[3,4]]
Output
2
Explanation

Nodes 0, 1, 2 form one component, and nodes 3, 4 form another component.

Example 2
Input
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output
1
Explanation

All nodes are connected in a single path.

Need a Hint?
세트나 힙과 같은 그래프 관련 데이터 구조를 사용해 보세요.
Edge Cases to Watch
  • 빈 입력 구조
  • 단일 요소 입력
  • 큰 수치 범위

해결할 준비가 되셨나요?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

편집기에서 열기
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.