#include<bits/stdc++.h>

#define MAX_N 200001

using namespace std;

list<pair<int,int> > ADJ[MAX_N];
vector<int> v(MAX_N, -1);
queue<int> clearq;
queue<int> iceq;


int CoalManBFS(int target){

    int8_t state = 0;
    int cost = 0;
    
    while(!iceq.empty()||!clearq.empty()){
        if(state){
            int curr = iceq.front();
            if(v[curr]==-1){
                v[curr] = cost;
                if(curr==target) return cost;
                for(const auto& x : ADJ[curr]){
                    if(x.second) iceq.push(x.first);
                    else clearq.push(x.first);
                }
            }
            iceq.pop();
            if(iceq.empty()){
                state = 0;
                cost++;
            }
        }
        else{
            int curr = clearq.front();
            if(v[curr]==-1){
                v[curr] = cost;
                if(curr==target) return cost;
                for(const auto& x : ADJ[curr]){
                    if(x.second) iceq.push(x.first);
                    else clearq.push(x.first);
                }
            }
            clearq.pop();
            if(clearq.empty()){
                state = 1;
                cost++;
            }
        }
    }

    return -1;
}


int main(){
    int n, m;
    cin >> n >> m;
    for(int i=0;i<m;i++){
        int x,y,t;
        cin >> x >> y >> t;
        ADJ[x].push_back({y,t});
        ADJ[y].push_back({x,t});
    }
    int p,q;
    cin >> p >> q;
    clearq.push(p);
    cout<< CoalManBFS(q)<< endl;
    return 0;
}