#define MAXN 200000
#include <iostream>
#include <vector>
#include <unordered_set>
#include <queue>


using namespace std;
int n, m;
vector<pair<int, int> > neighbours[MAXN];
int u, v;
unordered_set<int> visited;
queue< pair<int, int> > q[2];

int main()
{
    cin >> n >> m;

    while (m > 0) {
        int a, b, t;
        cin >> a >> b >> t;
        neighbours[a].emplace_back(b, t);
        neighbours[b].emplace_back(a, t);
        m--;
    }
    int stateSwitchCnt = 0;
    cin >> u >> v;

    q[0].push({u, 0});
    while (!q[0].empty()){
        while (!q[0].empty()) {
            int state = q[0].front().second;
            int node = q[0].front().first;
            q[0].pop();
            q[1].push({node, state});
            if (node == v) {
                cout <<  stateSwitchCnt;
                return 0;
            }
            else visited.insert(node);
            for (auto& neighbour: neighbours[node]) if (neighbour.second == state && visited.count(neighbour.first) == 0) {
                q[0].push({neighbour});
            }
        }
        stateSwitchCnt++;
        while (!q[1].empty()) {
            int state = q[1].front().second;
            int node = q[1].front().first;
            q[1].pop();
            for (auto& neighbour: neighbours[node]) if (neighbour.second == 1 - state && visited.count(neighbour.first) == 0 ) {
                    q[0].push({neighbour});
                }
        }

    }

    cout <<  -1;
    return 0;
}