Palindrome Walk

Given an undirected labeled graph, find the length of the shortest walk from vertex 0 to vertex 1 whose edge-label string is a palindrome, or -1 if none exists.

Medium7BFSGraphStringDynamic programmingInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

You are given an undirected graph GG with NN vertices. The vertices are numbered 0 through N1N-1, and one lowercase letter is written on each edge.

A walk is a route that may pass through the same vertex and the same edge more than once. The length of a walk is the number of edges it uses. The value of a walk is the string obtained by concatenating the letters on its edges in the order they are used.

A palindrome is a string that reads the same forward and backward. "a", "abba", and "racecar" are palindromes.

Among the walks that start at vertex 0 and end at vertex 1, find the ones whose value is a palindrome, and report the length of the shortest such walk.

Input

The first line contains the number of vertices NN and the number of edges MM. (2N202 \le N \le 20, 1MN(N1)/21 \le M \le N(N-1)/2)

Each of the next MM lines contains one edge as aa, bb, cc, separated by spaces. aa and bb are the numbers of the two vertices the edge joins, and cc is the lowercase letter written on that edge. The two endpoints of an edge are always different, and at most one edge joins any pair of vertices. The graph is not guaranteed to be connected.

Output

Print the minimum length of a walk from vertex 0 to vertex 1 whose value is a palindrome. Print -1 if no such walk exists.