All problems

Problem 929

Keys and Rooms

Medium · 20 pts · Graph, Depth-First Search, Breadth-First Search

Problem

There are N rooms numbered 0 to N - 1, and all are locked except room 0. Each room contains some keys, and a key with number k opens room k. You start in room 0, can pick up every key you find, and can enter any room you have a key for. Decide whether you can visit every room. Treat the keys as directed edges and run a depth-first or breadth-first search from room 0.

Input

The first line contains N. Each of the next N lines describes one room: the number of keys K, followed by the K key numbers.

Output

Print YES if every room can be visited, otherwise NO.

Constraints

1 <= N <= 1000; the total number of keys is at most 3000; 0 <= key < N

Example input

4
1 1
1 2
1 3
0

Example output

YES

Explanation

Room 0 holds key 1, room 1 holds key 2 and room 2 holds key 3, so you can walk through rooms 0, 1, 2 and 3 in order. Every room is visited, so the answer is YES.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Validate Binary Tree Nodes Next: All Paths From Source to Target