#include<bits/stdc++.h>
using namespace std;

using ll = long long;

const int mxN = 200007;
const int INF = 1e9;
vector<pair<int, int>> adj[mxN];
vector<int> visited(mxN);
vector<int> change(mxN, INF);
queue<pair<int, int>> q;

void dfs(int node, int state, int cnt)
{
 //   cout << "Posetio " << node << "\n";
    if (visited[node] == true) {
        return;
    }

    visited[node] = true;
    change[node] = min(cnt, change[node]);

    for (auto next : adj[node]) {
        if (visited[next.first]) continue;

        if (next.second != state) {
     //       cout << "Menjam stanje " << next.first << "\n";
            q.push({next.first, state ^ 1});
            change[next.first] = min(cnt + 1, change[next.first]);
        } 
        else dfs(next.first, state, cnt);
    }
}

void bfs(int node)
{

    int state;
    int curr;
    while(!q.empty()) {
        curr = (q.front()).first; 
        state = (q.front()).second;
   //     cout << "---- Obradjujem " << curr << "...\n";
        q.pop();

        dfs(curr, state, change[curr]);

    }
}

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

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

    for (int i = 0; i < m; i++) {
        int a, b, t;
        cin >> a >> b >> t;
        adj[a].push_back({b, t});
        adj[b].push_back({a, t});
    }

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

    change[u] = 0;
    q.push({u, 0});
    bfs(u);

    cout << ((change[v] == INF) ? -1 : change[v]) << "\n";

    return 0;
}