Consider 26 different substances, labeled 'A' through 'Z' (quotes for clarity only). Some of these substances can be created from the others by an alchemical reaction. Each alchemical reaction takes at least two different substances. Exactly 1 gram of each input substance is combined, causing an explosion. After the dust settles, we are left with just 1 gram of the resulting substance.
Alchemists don't like extra work, thus, for any given substance, there's at most one known reaction that results in that substance.
You are given a String initial describing the substances that you have initially. Each occurrence of a letter indicates 1 gram, so if a letter appears k times in initial, it means you have k grams of that substance. You are also given a String[] reactions describing all the possible alchemical reactions. Each element of reactions describes a single reaction and is formatted as "ingredients->result" (quotes for clarity only), where ingredients is the list of substances consumed and result is the substance produced. Return the minimal number of reactions required to obtain at least 1 gram of the substance 'X', or -1 if it is impossible.
|