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

typedef pair<int, int> pi;

const int INF = 200020;
int dist[INF];
int visited[INF];
int states[INF] = {-1};
vector<pi> graf[INF]; //prvo ide indeks cvora, pa tip puta

int main()
{
    int n,m, s, c; // n je broj cvorova dok je m broj grana
    bool nadjen = false;
    cin >> n >> m;

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

    cin >> s >> c;
    for (int i = 1; i <= n; i++){
        if(i == s){
            dist[i] = 0;
            states[i] = 0;
        }
        else{
            dist[i] = 200020;
            states[i] = -1;
        }
    }
    priority_queue<pi, vector<pi>, greater<pi>> pq;
    pq.push({0, s});

    while(!pq.empty()){
        pi root = pq.top();
        pq.pop();

        int mini = root.second;
        visited[mini] = true;

        if(dist[mini] != root.first) continue;

        if(m == 0){
            cout << -1 << endl;
            nadjen = true;
            break;
        }
        if(visited[c]) {
            cout << dist[c] << endl;
            nadjen = true;
            break;
        }

        for(auto u : graf[mini]){
            int v = u.first;
            if(!visited[v]){
                int stanje = u.second;

                int w = 0;
                if(stanje != states[mini])
                   w = 1;

                if(dist[mini] + w < dist[v]){
                    dist[v] = dist[mini] + w;
                    states[v] = stanje;
                    pq.push({dist[v], v});
                }
            }

        }

    }
    if(!nadjen) cout << -1;



    return 0;
}