Dsa
Graphs Bfs
Medium
Vacation Planner
You are planning a vacation that involves visiting a series of cities. Each city can have direct connections to other cities, and you must ensure that the travel plan allows you to visit all cities exactly once before returning to the starting city, creating a loop. Write a program that detects if a valid itinerary exists (i.e., a Hamiltonian cycle) in a given directed graph of cities and their connections.
Input format:
The first line contains an integer n (number of cities).
The next lines contain the city connections in the format: source city - destination city.
Output format:
Output 'YES' if a valid itinerary exists, otherwise output 'NO'.
Example:
Input:
4
0 1
1 2
2 3
3 0
Output:
YES
Key concepts
graphsbfstravelitinerary
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