#include <bits/stdc++.h>

using namespace std;

vector<vector<int>> graf;
vector<vector<bool>> graftip;

vector<int> dist;
vector<bool> visited;
vector<bool> gstatus;

priority_queue <int, vector<int>, greater<int>> q;

int main()
{
    int n;
    int m;

    cin >> n;
    cin >> m;

    for(int i = 0; i < n; i++)
    {
        vector<int> a;
        vector<bool> b;

        graf.push_back(a);
        graftip.push_back(b);

        dist.push_back(INT_MAX);
        visited.push_back(false);
        gstatus.push_back(false);
    }

    for(int i = 0; i < m; i++)
    {
        int a;
        int b;
        bool t;

        cin >> a;
        cin >> b;
        cin >> t;

        graf[a - 1].push_back(b - 1);
        graf[b - 1].push_back(a - 1);
        graftip[a - 1].push_back(t);
        graftip[b - 1].push_back(t);
    }

    int u;
    int v;

    cin >> u;
    cin >> v;

    u--;
    v--;

    dist[u] = 0;

    q.push(u);
    bool status = false;

    while(!q.empty())
    {

        int x = q.top();
        q.pop();
        status = gstatus[x];

        if(!visited[x])
        {
            visited[x] = true;


            for(int i = 0; i < graf[x].size(); i++)
            {
                bool promena = false;
                if(!visited[graf[x][i]])
                {
                    int alt = dist[x];

                    if(graftip[x][i] != status)
                    {
                        alt++;
                        promena = true;
                    }

                    if(alt < dist[graf[x][i]])
                    {
                        q.push(graf[x][i]);
                        dist[graf[x][i]] = alt;

                        if(promena)
                            gstatus[graf[x][i]] = !gstatus[x];
                    }
                }
            }
        }
    }

    if(dist[v] == INT_MAX)
        cout << -1 << '\n';
    else
        cout << dist[v] << '\n';


    return 0;
}