Binary Roads

Ali's carried value flips after every road, so each edge is usable only when its label matches his value; find the shortest 0-1 walk from node 0 to node N-1, or -1.

Medium6GraphBFSShortest pathNo attempts yetTime limit3sMemory limit64 MB

Problem

Ali is on a trip and wants to reach one particular place as fast as he can.

Treat the area as a graph with NN places and EE roads. The places are numbered from 00 to N1N-1 and every road is bidirectional. Walking one road takes 1 hour, and Ali may pass through the same place or the same road any number of times.

Ali starts at place 00 and his destination is place N1N-1.

Every road carries a value of 00 or 11, and Ali carries a value of 00 or 11 as well. Ali may walk a road only when the value of the road equals his own value. His value flips as soon as he finishes walking a road: 00 becomes 11 and 11 becomes 00. It flips again after the next road.

Ali chooses his starting value himself. He may start with 00 or with 11. Find the shortest time in hours that he needs to reach place N1N-1.

Input

The first line contains two integers NN and EE (1N2000001 \le N \le 200\,000, 0E10000000 \le E \le 1\,000\,000).

Each of the next EE lines contains three integers AA, BB and VV. They describe a bidirectional road between place AA and place BB whose value is VV. No two roads join the same pair of places with the same value.

For every road, ABA \ne B, 0A,B<N0 \le A, B < N, and VV is 00 or 11.

Output

Print one integer, the shortest time in hours for Ali to reach place N1N-1. Print -1 if he cannot reach it.

Notes

Ali may walk through a place or a road again, so a detour taken only to change his value is allowed. A road that leads straight to the destination is unusable at a moment when his value differs from the value of that road.