#C11001. Can Visit All Rooms
Can Visit All Rooms
Can Visit All Rooms
You are given several datasets. In each dataset, there are n rooms numbered from 1 to n. Each room has a list of keys to other rooms. The keys for a room are provided in the following format: the first integer of the line represents the room number, followed by zero or more integers representing keys to other rooms.
You start from room 1 and use the keys found to access other rooms. Your task is to determine whether it is possible to visit all the rooms starting from room 1. In other words, check if every room can be reached through the available keys.
Important: The input may consist of multiple datasets separated by a blank line.
Hint: Consider using a graph traversal algorithm such as depth-first search or breadth-first search.
inputFormat
The input is read from standard input (stdin
) and consists of one or more datasets. Each dataset is separated by a blank line.
For each dataset:
- The first line contains a single integer n (the number of rooms).
- The following n lines each describe a room. Each such line starts with an integer representing the room number, followed by zero or more integers which are the keys found in that room.
Note: The order of the datasets and rooms is guaranteed such that the first room in each dataset is room 1.
outputFormat
For each dataset, print a single line to standard output (stdout
) containing "YES" if it is possible to visit all rooms starting from room 1, otherwise print "NO".
2
1 2
2
YES