#include <bits/stdc++.h>

#define maxn 200005
#define FAST ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define pb push_back

using namespace std;

vector<pair<int, int> > adj[maxn];
priority_queue<pair<int, int> > q;
int dp[maxn];
int processed[maxn] = {};

int main()
{
    FAST

    int n, m;
    cin >> n >> m;
    for(int i = 0; i < m; i++){
        int u, v, k;
        cin >> u >> v >> k;
        adj[u].pb({v, k});
        adj[v].pb({u, k});
    }
    for(int i = 0; i < maxn; i++){
        dp[i] = 300000;
    }
    int u, v;
    cin >> u >> v;
    dp[u] = 0;
    q.push({0, u});
    while(!q.empty()){
        int a = q.top().second; q.pop();
        if(processed[a]) continue;
        processed[a] = 1;
        for(auto cvor : adj[a]){
            int b = cvor.first, l = cvor.second;
            int koef;
            if(l == 1){
                if(dp[a] % 2 == 0)
                    koef = 1;
                else
                    koef = 0;
            }
            else{
                if(dp[a] % 2 == 0)
                    koef = 0;
                else
                    koef = 1;
            }
            if(dp[a] + koef < dp[b]){
                dp[b] = dp[a] + koef;
                q.push({-dp[b], b});
            }
        }
    }
    if(dp[v] == 300000) cout << "-1" << endl;
    else cout << dp[v] << endl;

    return 0;
}