#include <iostream>
#include <vector>
#include <set>
#define forn(i, n) for (int i = 0; i < n; i++)
using namespace std;
const int oo = 2e5+7;
int n, m;
vector<pair<int, int>> conn[oo];
int dsu[oo][2], drank[oo][2];
int parent(int a, int p) {
    if (dsu[a][p] == a) return a;
    return dsu[a][p] = parent(dsu[a][p], p);
}
void unite(int a, int b, int p) {
    a = parent(a, p), b = parent(b, p);
    if (a == b) return;
    if (drank[a][p] < drank[b][p]) swap(a, b);
    dsu[b][p] = a;
    drank[a][p]++;
}
void dfs(int a, int p, int parent, vector<bool>& visited) {
    if (visited[a]) return;
    if (parent != -1) unite(a, parent, p);
    visited[a] = true;
    for (auto e: conn[a]) {
        if (e.second != p) continue;
        if (e.first == parent) continue;
        dfs(e.first, p, a, visited);
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    forn(i, n) forn(j, 2) dsu[i][j] = i, drank[i][j] = 0;
    forn(i, m) {
        int a, b, t;
        cin >> a >> b >> t;
        a--, b--;
        conn[a].push_back({b, t});
        conn[b].push_back({a, t});
    }
    vector<bool> visited(n, false);
    forn(i, n) dfs(i, 0, -1, visited);
    visited.assign(n, false);
    forn(i, n) dfs(i, 1, -1, visited);

    set<int> niggaconns[n];
    forn(i, n) {
        niggaconns[parent(i, 0)].insert(parent(i, 1));
        niggaconns[parent(i, 1)].insert(parent(i, 0));
    }
    visited.assign(n, false);
    int u, v;
    cin >> u >> v;
    u--, v--;
    vector<int> visiting_now = {parent(u, 0)}, future_visit;
    vector<int> dist(n, -1);
    dist[visiting_now[0]] = 0;
    while (visiting_now.size()) {
        for (int e: visiting_now) {
            for (int g: niggaconns[e]) if (dist[g] == -1) {
                dist[g] = dist[e] + 1;
                future_visit.push_back(g);
            }
        }
        visiting_now = future_visit;
        future_visit = {};
    }
    int f1 = dist[parent(v, 0)], f2 = dist[parent(v, 1)];
    if (f1 == -1) cout << f2 << endl;
    else if (f2 == -1) cout << f1 << endl;
    else cout << min(f1, f2) << endl;
}