#include <bits/stdc++.h>

using namespace std;

struct edge
{
    int startN,endN,w;
};

struct node
{
    vector<edge> conn;
};

int main()
{
    int N,M;
    cin >> N >> M;
    vector<node> nodes(N+1);
    for(int i = 1;i<=M;i++)
    {
        int t1,t2,t3;
        edge temp;
        cin >> t1 >> t2 >> t3;
        temp.startN = t1;
        temp.endN = t2;
        temp.w = t3;
        nodes[t1].conn.push_back(temp);

        temp.startN = t2;
        temp.endN = t1;
        temp.w = t3;
        nodes[t2].conn.push_back(temp);
    }

    int u,v;
    cin >> u >> v;

    vector<int> chng(N+1,numeric_limits<int>::max());
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > pq;
    pq.push(make_pair(0,u));
    chng[u] = 0;
    while(!pq.empty())
    {
        int t = pq.top().second;
        pq.pop();
        for(int i = 0;i<nodes[t].conn.size();i++)
        {
            int n = nodes[t].conn[i].endN;
            int w = nodes[t].conn[i].w;

            //cout << "change state[t] = " << chng[t] << " w = " << w << " chng[n] = " << chng[n] << endl;
            if((chng[t] % 2) == w && chng[n] > chng[t])
            {
                chng[n] = chng[t];
                pq.push(make_pair(chng[n], n));
            }
            else if((chng[t] % 2) != w && chng[n] > chng[t]+1)
            {
                chng[n] = chng[t]+1;
                pq.push(make_pair(chng[n], n));
            }
        }
    }

    if(chng[v] == numeric_limits<int>::max())
        chng[v] = -1;
    cout << chng[v] << endl;


    return 0;
}