#include <bits/stdc++.h>
#define INT_MAX 10e9

using namespace std;
typedef long long ll;

int graph[1000000][3];


void BellmanFord(int V, int E, int src, int goal)
{
    // Initialize distance of all vertices as infinite.
    int dis[V];
    for (int i = 0; i < V; i++)
        dis[i] = INT_MAX;

    // initialize distance of source as 0
    int k;
    dis[src-1] = 0;
   // for (int i = 0; i < V - 1; i++) {
        for (int j = 0; j < E; j++) {
                if(graph[j][0] == src)
                    k = 0;
              //  cout<<"\n"<<k;
            if (k != graph[j][2]){
                if (dis[graph[j][0]-1] != INT_MAX && dis[graph[j][0]-1] + 1 < dis[graph[j][1]-1]){
                    dis[graph[j][1]-1] = dis[graph[j][0]-1] + 1;
                    k = graph[j][2];
                }
            }
            else
                if (dis[graph[j][0]-1] != INT_MAX && dis[graph[j][0]-1] <= dis[graph[j][1]-1])
                        dis[graph[j][1]-1] = dis[graph[j][0]-1];
           // cout<<"\n"<<dis[graph[j][0]-1]<<" "<<dis[graph[j][1]-1];

        }
   // }

    if(dis[goal-1] == 2147483647)
        cout << "-1";
    else
        cout<< dis[goal-1] <<"\n";

}

int main()
{
    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    ll V, E, a, b, k, p, q, br=0;
    cin>>V;
    cin>>E;

    for(int i=0;i<E;i++){
        cin>>a>>b>>k;
        graph[i][0]=a;
        graph[i][1]=b;
        graph[i][2]=k;
        if(k==1)
            br++;
    }

    cin>>p>>q;

    if(br == E)
    {
        cout<<"1";
        return 0;
    }
    BellmanFord(V, E, p, q);




    return 0;
}