#include <bits/stdc++.h>

using namespace std;
int vel;
int m;
int pocetak;
int kraj;
const int INF = 1000000000;
vector<pair<int,int>> adj[5000000];

void dijkstra(int s, vector<int> & d)
{
    int n = 2*vel;
    d.assign(n+1, INF);
    vector<bool> u(n+1, false);

    d[s] = 0;
    for (int i = 1; i <= n; i++) {
        int v = -1;
        for (int j = 1; j <= n; j++) {
            if (!u[j] && (v == -1 || d[j] < d[v]))
                v = j;
        }

        if (d[v] == INF)
            break;

        u[v] = true;
        for (auto edge : adj[v]) {
            int to = edge.first;
            int len = edge.second;

            if (d[v] + len < d[to]) {
                d[to] = d[v] + len;
            }
        }
    }
}

int main()
{
    cin>>vel>>m;
    for(int i=0;i<m;i++)
    {
        int a,b,d;
        cin>>a>>b>>d;
        if(d==1)
        {
            adj[a].push_back(make_pair(b+vel,1));
            adj[a+vel].push_back(make_pair(b+vel,0));
            adj[b+vel].push_back(make_pair(a+vel,0));
            adj[b].push_back(make_pair(a+vel,1));
        }
        if(d==0)
        {
            adj[a].push_back(make_pair(b,0));
            adj[b].push_back(make_pair(a,0));
            adj[a+vel].push_back(make_pair(b,1));
            adj[b+vel].push_back(make_pair(a,1));
        }
    }
    cin>>pocetak>>kraj;
    vector<int> dist;
    dijkstra(pocetak,dist);
    int rez1=dist[kraj];
    int rez2=dist[kraj+vel];
    int min1=min(rez1,rez2);
    dijkstra(pocetak+vel,dist);
    int rez3=dist[kraj]+1;
    int rez4=dist[kraj+vel]+1;
    int min2=min(rez3,rez4);
    cout<<min(min1,min2)<<endl;
    return 0;
}