using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace tak._3
{
    class Program
    {
        struct Sante
        {
            public int a;
            public int b;
            public int t;
        }

        static void Main(string[] args)
        {
            string[] pom = Console.ReadLine().Split();
            int n = int.Parse(pom[0]);
            int m = int.Parse(pom[1]);
            Sante[] niz = new Sante[m];
            for (int i = 0; i < niz.Length; i++)
            {
                pom = Console.ReadLine().Split();
                niz[i].a = int.Parse(pom[0]);
                niz[i].b = int.Parse(pom[1]);
                niz[i].t = int.Parse(pom[2]);  
            }
            pom = Console.ReadLine().Split();
            int u = int.Parse(pom[0]);
            int v = int.Parse(pom[1]);
            int br = 0;
            int uPom = u;
            int prStanje; bool flag = true; int maxIter = 0; int p;
            while (flag&&maxIter<niz.Length)
            {
                u = uPom; prStanje = 0;
                for (p = maxIter; p < niz.Length; p++)
                {
                    if (niz[p].a == u)
                    {
                        u = niz[p].b;
                        if (niz[p].t != prStanje)
                        {
                            prStanje = niz[p].t;
                            br++;
                        }

                    }
                }
                if (u == v)
                    flag = false;
                else
                    br = 0;
                maxIter++;
            }
            if (u != v)
                br = -1;
            Console.WriteLine(br);
        }
    }
}