#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iomanip> 
#include <map>
#include <string>
#include <list>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <iterator>
#include <queue>
#include <set>


#define f(n) for (long long i = 0; i < n; i++)
#define f0(n) for (int j = 0; j < n; j++)
#define co(n) cout << n << "\n";

using namespace std;

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n, m;
    cin >> n >> m;

    map<pair<int,int>, int> mg;

    f(m)
    {
        int a, b, t;
        cin >> a >> b >> t;
        mg[pair<int, int>(a - 1, b - 1)] = t + 1;
        mg[pair<int, int>(b - 1, a - 1)] = t + 1;
    }

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



    vector<int> xd(1);
    xd.push_back(u);

    map<int, bool> dd;
    f(n) dd[i] = false;
    dd[u] = true;

    vector<int> d(n);
    f(n) d[i] = -1;
    d[u] = 0;

    map<int, set<int>> dn;
    dn[0].insert(u);


    int k = 0;
    while (xd.size() < n + 1 && d[v] == -1)
    {
        int z = dn[k].size();
        for (int l : dn[k])
        {
            f(n)
            {
                int t = mg[pair<int, int>(l, i)];
                if (t != 0)
                {
                    if (d[i] == -1)
                    {
                        if (t - 1 == k % 2)
                        {
                            dn[k].insert(i);
                            d[i] = k;
                        }
                        else
                        {
                            dn[k + 1].insert(i);
                            d[i] = k + 1;
                        }
                        xd.push_back(i);
                    }
                    else
                    {
                        if (t - 1 == k % 2)
                        {
                            if (d[i] > k)
                            {
                                dn[k].insert(i);
                                d[i] = k;
                            }
                        }
                    }
                    dd[i] = true;
                }
            }
        }
        if (dn[k].size() == z) k++;
    }
    cout << d[v];
}