Learn
Exam

Graph Traversal

Difficulty
BEGINNER

Problem

You are given the number of vertices n and bidirectional edge information edges as input parameters. Write a function solution that returns the total number of vertices that can be reached starting from vertex 1, including vertex 1 itself.

For example, consider a graph with 6 vertices and 5 edges, as shown below:

Starting from vertex 1, you can reach vertices 2, 3, 4, and 5, including vertex 1, so the function should return 5.


Constraints

  • The number of vertices n is a natural number between 2 and 10,000 inclusive.
  • The bidirectional edge information edges is represented as a list of pairs (x, y), where:
    • Each element in edges represents an edge between vertices x and y.
    • The list edges can contain up to 1,000,000 edges.
    • Both x and y are natural numbers between 1 and n inclusive.

Test Case

Test Case Number n edges return
1 6 [[1,2],[1,3],[2,3],[2,4],[3,5]] 5
2 10 [[1,2],[1,4],[1,6],[2,3],[3,4],[3,7],[4,5],[5,6],[5,7],[5,8],[9,10]] 8
3 2 [[1,2]] 2

Explanation for Test Case 1

  • Starting from vertex 1, you can reach vertices {1, 2, 3, 4, 5}.

Explanation for Test Case 2

  • Starting from vertex 1, you can reach vertices {1, 2, 3, 4, 5, 6, 7, 8}.

Explanation for Test Case 3

  • Starting from vertex 1, you can reach vertices {1, 2}.

Notes

  • If an error (runtime error) occurs during test cases 17, 19, or 20 in the python development environment, refer to the following:
    • Python limits the maximum recursion depth to 1,000.
    • Deep recursion calls may result in a RecursionError, which is a type of runtime error.
    • To adjust the maximum recursion depth in Python, write code as shown below:
import sys  
sys.setrecursionlimit(10**6)  
 
def solution(n, edges):  
  return 0