#include <bits/stdc++.h>

using namespace std;
vector<pair<int,bool>> graf[200005];
const int INF = 200005;


int solve(int u, int n, int v){
    int d[n];
    bool stanje[n];
    bool resen[n];
    for(int i=0; i<n; i++){
        d[i] = INF;
        resen[i] = false;
    }
    d[u] = 0;
    stanje[u] = false;
    for(int i = 0; i<graf[u].size(); i++){
        d[graf[u].at(i).first] = 1-(int)(graf[u].at(i).second==stanje[u]);
        stanje[graf[u].at(i).first] = graf[u].at(i).second;
    }
    resen[u] = true;
    while(true){
        int s = INF;
        int c = -1;
        for(int i = 0; i<n; i++){
            if(!resen[i]&&d[i]<s){
                c = i;
                s = d[i];
            }
        }
        if(c==-1){
            break;
        }
        for(int i = 0; i<graf[c].size(); i++){
            if(d[c] + 1-(int)(stanje[c]==graf[c].at(i).second)<d[graf[c].at(i).first]){
                d[graf[c].at(i).first] = d[c] + 1-(int)(stanje[c]==graf[c].at(i).second);
                stanje[graf[c].at(i).first] = graf[c].at(i).second;
            }
        }
        resen[c] = true;
        if(c==v){
            return d[v];
        }
    }
    if(d[v]==INF){
        return -1;
    }
    return d[v];
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i = 0; i<m; i++){
        int a,b,t;
        cin>>a>>b>>t;
        a--;
        b--;
        graf[a].push_back({b,(bool)t});
        graf[b].push_back({a,(bool)t});
    }
    int u, v;
    cin>>u>>v;
    u--;
    v--;
    cout<<solve(u,n,v);
    return 0;
}