Dsa
Graphs Bfs
Medium
City Connectivity
In a city represented as a graph, each node represents a city and each edge represents a direct road between two cities. Given the city connections, write a program to check if all cities are reachable from a given city. The cities are represented as integers starting from 0 to N-1.
Input format:
- The first line contains two integers N and M, where N is the number of cities and M is the number of roads.
- The next M lines each contain two integers, u and v, representing a road from city u to city v.
Output format:
- Output 'YES' if all cities are reachable from the given starting city (city 0), otherwise output 'NO'.
Example:
Input:
5 4
0 1
0 2
1 3
2 4
Output:
YES
Key concepts
graphsbfsconnectivity
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now