#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned u;

#define INF INT_MAX
#define MOD (1e9+7)
#define PI arccos(-1)

#define pll pair<long long, long long>
#define mp make_pair

#define vll vector<ll>
#define vb vector<bool>
#define vs vector<string>
#define vp vector<pll>
#define pb push_back
#define all(v) v.begin(), v.end()
#define print_vect(v) for (auto it : v) cout << it << " ";

#define pq priority_queue<ll>
#define setll set<ll>
#define mset multiset<ll>
#define queue queue<ll>

ll nzs(ll a, ll b){ 
    return (a / __gcd(a, b)) * b; 
}

ll typeDiff(ll x, ll y){
    return x != y;
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll nodes, edges;
    cin >> nodes >> edges;
    vector<vp> graf(nodes);
    for(ll i = 0 ; i < edges ; i++){
        ll x, y, t;
        cin >> x >> y >> t;
        x--;
        y--;
        graf[x].push_back(mp(y, t));
        graf[y].push_back(mp(x, t));
    }
    ll root, dest;
    cin >> root >> dest;
    root--;
    dest--;
    vp dijkstra(nodes, mp(INF, 0));
    vb visited(nodes, false);
    dijkstra[root] = mp(0, 0);
    visited[root] = true;
    set<pll> s;
    s.insert(mp(0, root));
    while(!s.empty()){
        ll node = (*s.begin()).second;
        s.erase(s.begin());
        for(auto x : graf[node]){
            if(!visited[x.first]){
                if(dijkstra[x.first].first > dijkstra[node].first + typeDiff(dijkstra[node].second, x.second)){
                    dijkstra[x.first].first = dijkstra[node].first + typeDiff(dijkstra[node].second, x.second);
                    dijkstra[x.first].second = x.second;
                    s.insert(mp(dijkstra[x.first].first, x.first));
                }
            }
        }
    }
    if(dijkstra[dest].first == INF){
        cout << -1;
    }
    else{
        cout << dijkstra[dest].first;
    }
    return 0;
}