#include <bits/stdc++.h>

using namespace std;

#define MAXS 200001
#define INF 500000

vector<vector<pair<int, int>>> adj;
int dp_stanje[MAXS];
int dp_promene[MAXS];


bool postoji_put(int src, int dst)
{
    if (src == dst)
        return true;

    int n = (int)adj.size();

    vector<bool> visited(n, false);

    queue<int> q;

    visited[src] = true;
    q.push(src);

    while (!q.empty())
    {
        src = q.front();
        q.pop();

        for (auto x : adj[src])
        {
           if (x.first == dst)
                return true;

            if (!visited[x.first])
            {
                visited[x.first] = true;
                q.push(x.first);
            }
        }
    }

    return false;
}


void racunaj(int src, int dst)
{
    int n = (int)adj.size();

    vector<bool> visited(n, false);

    queue<int> q;

    visited[src] = true;
    q.push(src);

    dp_promene[src] = 0;

    while (!q.empty())
    {
        src = q.front();
        q.pop();

        for (auto x : adj[src])
        {
           //if (x.first == dst)
          //      continue;

            if (!visited[x.first])
            {
                visited[x.first] = true;
                q.push(x.first);

                dp_stanje[x.first] = x.second;
                if (dp_stanje[x.first] != dp_stanje[src])
                {
                    dp_promene[x.first] = min(dp_promene[x.first], dp_promene[src] + 1);
                }
            }
        }
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie();

    int n, m, a, b, t, u, v;
    bool svi_jednaki = true;

    cin >> n >> m;
    adj = vector<vector<pair<int, int>>>(n + 1);

    for (int i = 0; i < m; i++)
    {
        cin >> a >> b >> t;
        adj[a].push_back(make_pair(b, t));
        adj[b].push_back(make_pair(a, t));
        if (svi_jednaki && (t != 1))
        {
            svi_jednaki = false;
        }
    }

    cin >> u >> v;


    if (postoji_put(u, v))
    {
        if (svi_jednaki)
        {
            cout << 1 << endl;
        }
        else
        {
            //memset(dp_promene, INF, MAXS);
            for (int i = 0; i < MAXS; i++)
            {
                dp_promene[i] = INF;
            }
            racunaj(u, v);
            cout << dp_promene[v] << endl;
        }
    }
    else
    {
        cout << -1 << endl;
    }



    return 0;
}