Little Billy enjoys riding the bus. Whenever he is bored he decides to go on a bus trip.
There are N bus stations in Billy's town, numbered from 0 to N-1, and some bus routes connecting some of them. Little Billy starts at station 0, at time 0, waits for the next bus to arrive and takes it. Note that little Billy can take a bus that leaves station 0 at time 0. The constraints guarantee that there will always be at least one bus route that passes through station 0. He gets off at the next bus stop along the route, waits for another bus to arrive at that station, and takes it. He rides the bus to the next stop and waits for another bus, and so on. Note that Billy must take a bus at a time strictly greater than the time he arrived at that station. If multiple buses arrive at the same station at the same time, Billy takes the one that comes first in the input (see below). He stops as soon as he returns to station 0.
You will be given a String[] buses describing each of the bus routes in Billy's town. The ith element of buses will be a space delimited list of integers representing the locations, in order, along the ith bus route. The route of each bus is cyclic, meaning that when the bus is at the last station in the list, it goes to the first station in the list and continues its route from the start. Each bus starts its route at time 0. The time it takes for a bus to travel between two locations, in minutes, is equal to the absolute difference between the numbers. Note that two bus routes could be identical.
For example, the route of a bus described by the string "0 4 2" is as follows: it starts at time 0 in station 0 and arrives at station 4 at time 4. Next, it arrives at station 2 at time 6, and back at station 0 at time 8. The bus continues its route and arrives at station 4 at time 12, then at station 2 at time 14, back to station 0 at time 16, and so on.
Return the number of minutes it takes Billy to return to station 0. If he doesn't get back to station 0 in 1000 minutes or less, return -1 instead.
|