using System;
using System.Collections.Generic;

namespace santeleda
{
    class Program
    {
        static int masina = 0;
        static long br = 0;
        static long mini = long.MaxValue;
        static List<int> poseceni = new List<int>();
        static long put(long r1, long r2, List<Tuple<long, long>>[] lista, bool prolaz)
        {
            poseceni.Add((int)r1);
            if (prolaz)
            {
                if (r1 == r2)
                {
                    if (br < mini) mini = br;
                    br = 0;
                    return mini;
                }
                for (int i = 0; i < lista[r1].Count; i++)
                {
                    if (!poseceni.Contains((int)lista[r1][i].Item1))
                    {
                        if (lista[r1][i].Item2 == 1 && masina == 0)
                        {
                            masina = 1; br++;
                        }
                        else if (lista[r1][i].Item2 == 0 && masina == 1)
                        {
                            masina = 0; br++;
                        }
                        put(lista[r1][i].Item1, r2, lista, true);
                    }
                }
                return put(r1, r2, lista, false);
            }
            else return mini;
        }
        static void Main(string[] args)
        {
            string[] unos = Console.ReadLine().Split();
            int N = int.Parse(unos[0]);
            int M = int.Parse(unos[1]);
            List<Tuple<long, long>>[] lista = new List<Tuple<long, long>>[N];

            for (int i = 0; i < N; i++) lista[i] = new List<Tuple<long, long>>();

            for(int i = 0; i < M; i++)
            {
                string[] unos1 = Console.ReadLine().Split();
                lista[long.Parse(unos1[0]) - 1].Add(Tuple.Create(long.Parse(unos1[1]) - 1, long.Parse(unos1[2])));
                lista[long.Parse(unos1[1]) - 1].Add(Tuple.Create(long.Parse(unos1[0]) - 1, long.Parse(unos1[2])));
            }
            string[] unos2 = Console.ReadLine().Split();
            int a = int.Parse(unos2[0]);
            int b = int.Parse(unos2[1]);

            long pom = put(a - 1, b - 1, lista, true);
            if (pom == long.MaxValue) Console.WriteLine(-1);
            else Console.WriteLine(pom);
        }
    }
}