#include <bits/stdc++.h>

using namespace std;
vector<pair<int,int>> adj[20001];
int d[20001][2];


int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, m; cin >> n >> m;
    for(int i=0;i<m;i++){
        int u, v, c; cin >> u >> v >> c;
        adj[u].push_back({v, c});
        adj[v].push_back({u, c});
    }
    for(int i=0;i<=n;i++){
        d[i][0]=d[i][1]=3e6;
    }
    int start, finish; cin >> start >> finish;
    d[start][0]=0;
    d[start][1]=1;
    deque<int> dq;
    dq.push_front(start);
    for(;!dq.empty();){
        int v = dq.front();
        //cout << v << ' ' << d[v][0] << ' ' << d[v][1] <<  '\n';
        dq.pop_front();
        for(auto u:adj[v]){
            if(d[v][0]+u.second < d[u.first][u.second]){
                d[u.first][u.second]=d[v][0]+u.second;
                if(u.second==0){
                    dq.push_front(u.first);
                }
                else dq.push_back(u.first);
            }
            if(d[v][1]+1-u.second < d[u.first][u.second]){
                d[u.first][u.second]=d[v][1]+1-u.second;
                if(u.second==1){
                    dq.push_front(u.first);
                }
                else dq.push_back(u.first);
            }
        }
    }
    int ans = min(d[finish][0],d[finish][1]);
    if(ans == 3e6) ans = -1;
    cout << ans;
    return 0;
}