#include <bits/stdc++.h>
#define pb push_back
#define xx first
#define yy second
#define ll long long
#define all(x) (x).begin(),(x).end()

using namespace std;
const int INF = 1000000000;
vector<vector<pair<int, int>>> adj;

void dijkstra(int s, vector<int> & d, vector<int> & p) {
    int n = adj.size();
    d.assign(n, INF);
    p.assign(n, -1);

    d[s] = 0;
    p[s]=0;
    set<pair<int, int>> q;
    q.insert({0, s});
    while (!q.empty()) {
        int v = q.begin()->second;
        q.erase(q.begin());

        for (auto edge : adj[v]) {
            int to = edge.first;
            int len = edge.second;

            if (d[v] + (len!=p[v]) < d[to]) {
                q.erase({d[to], to});
                d[to] = d[v] + (len!=p[v]);
                p[to] = len;
                q.insert({d[to], to});
            }

        }
    }
}
int main(){
    //ios_base::sync_with_stdio(false);
    int n, m, x, y, t;
    cin>>n>>m;
    adj.resize(n);
    for(int i=0; i<m; i++){
        cin>>x>>y>>t;
        adj[x-1].pb({y-1, t});
        adj[y-1].pb({x-1, t});
    }
    cin>>x>>y;
    vector<int> d(n);
    vector<int> p(n);
    dijkstra(x-1, d, p);
    if(d[y-1]==INF) cout<<-1;
    else cout<<d[y-1];
    return 0;
}