#include <bits/stdc++.h>

#define xx first
#define yy second
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define mp make_pair
#define pb push_back
#define popb pop_back
#define ez {cout << "NO\n"; return;}

using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef string str;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int MAX=1e6+3;
int n, m, root, dest;
vector<pii> g[MAX];
bool v[MAX];
queue<pii> q;
vector<int> tr;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);

    cin >> n >> m;
    for(int i=0;i<m;++i){
        int a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        g[a].pb({b, c});
        g[b].pb({a, c});
    }
    cin >> root >> dest;
    root--; dest--;
    q.push({root, 1});
    int sw=0, res=-1, br=0;
    while(true){
        while(!q.empty()){
            auto s=q.front();
            q.pop();
            //cout << ": " << s.xx+1 << "\n";
            v[s.xx]=1;
            res=s.yy;
            if(s.xx==dest){
                cout << s.yy-1 << "\n";
                return 0;
            }
            tr.pb(s.xx);
            for(int i=0;i<g[s.xx].size();++i){
                if(g[s.xx][i].yy==sw && v[g[s.xx][i].xx]==0){
                    q.push({g[s.xx][i].xx, s.yy});
                    tr.pb(g[s.xx][i].xx);
                }
            }
        }
        if(tr.size()==0){
            br++;
            if(br>=3){
                cout << "-1\n";
                return 0;
            }
        }
        else br=0;
        sw^=1;
        for(auto node : tr){
            //cout << node+1 << " sw=" << sw << "\n";
            for(int i=0;i<g[node].size();++i){
                //cout << "-->" << g[node][i].xx+1 << ": " << sw << " " << g[node][i].yy << " " << v[g[node][i].xx] << " ";
                if(sw==g[node][i].yy && v[g[node][i].xx]==0){
                    //cout << "gg";
                    q.push({g[node][i].xx, res+1});
                }
                //cout << "\n";
            }
            tr.clear();
        }
        //cout << '\n';
    }

    return 0;
}