#include <bits/stdc++.h>

#define pb push_back
#define MAXN 200010

using namespace std;

int compCnt = 1;
vector<int> g[2][MAXN], graph[MAXN];
int comp[2][MAXN], dist[MAXN];

void make_comp(int u, int t, int c) {

    comp[t][u] = c;
    for(int v: g[t][u])
        if(!comp[t][v])
            make_comp(v, t, c);
}

int bfs(int src, int dest) {

    for(int i = 0; i < compCnt; i++)
        dist[i] = -1;

    queue<int> q;
    q.push(comp[0][src]);
    dist[comp[0][src]] = 0;
    while(!q.empty()) {
        int u = q.front();
        q.pop();

        if(u == comp[0][dest] || u == comp[1][dest])
            return dist[u];
        
        for(int v: graph[u]) {
            if(dist[v] == -1) {
                q.push(v);
                dist[v] = dist[u] + 1;
            }
        }
    }
    return -1;
}

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

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

    for(int i = 0; i < m; i++) {
        int u, v, t;
        cin >> u >> v >> t;
        u--; v--;

        g[t][u].pb(v);
        g[t][v].pb(u);
    }

    for(int t = 0; t < 2; t++)
        for(int i = 0; i < n; i++)
            if(!comp[t][i])
                make_comp(i, t, compCnt++);
    
    for(int i = 0; i < n; i++) {
        int u = comp[0][i], v = comp[1][i];
        graph[u].pb(v);
        graph[v].pb(u);
    }

    int u, v;
    cin >> u >> v;
    u--; v--;
    cout << bfs(u, v) << endl;
    return 0;
}