#include<bits/stdc++.h>
using namespace std;

struct put{
    int cvor; 
    short vr;
    put(int a, short b){cvor =a;vr = b;}
};

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    int N,M,start, end, min, minind;
    cin >> N >> M;
    vector<vector<put>> graf(N);
    
    int cv1, cv2;
    short vr;
    for(int i = 0; i < M; i++){
        cin >> cv1 >> cv2 >> vr;
        graf[cv1-1].push_back(put(cv2-1,vr));
    }
    cin >> start >> end;
    start--;end--;
    int duzina[N], neposeceni = N;
    fill_n (duzina, N, 500000);
    bool poseceni[N] = {false};
    short masina[N];
    duzina[start] = 0;
    masina[start] = 0;
    
    while(neposeceni > 0){
        min = 500000;
        for(int i = 0; i < N; i++)
            if(!poseceni[i] && (duzina[i] <= min)){
                min = duzina[i]; 
                minind = i;
            }
        //cout << minind <<"\n";
        poseceni[minind] = true;
        neposeceni--;
        for(int i = 0; i < graf[minind].size(); i++){
            //cout << minind << "-" << graf[minind][i].vr << "->" << graf[minind][i].cvor<< "\n";
            if(poseceni[graf[minind][i].cvor])continue;
            int trcvor = graf[minind][i].cvor;
            
            if(((masina[minind] == 2) || (masina[minind] == graf[minind][i].vr)) && (duzina[minind] < duzina[trcvor])){
                duzina[trcvor] = duzina[minind];
                masina[trcvor] = graf[minind][i].vr; 
                continue;}
                
            if((masina[minind] == 2) && (duzina[minind] == duzina[trcvor])){
                if(masina[trcvor] != graf[minind][i].vr) masina[trcvor] = 2; 
                continue;}
                
            if((masina[minind] != graf[minind][i].vr) && ((duzina[minind]+1) < duzina[trcvor])){
                duzina[trcvor] = duzina[minind]+1;
                masina[trcvor] = graf[minind][i].vr;
                continue;}
                
            if((masina[minind] != graf[minind][i].vr) && ((duzina[minind]+1) == duzina[trcvor]))
                if(masina[trcvor] != graf[minind][i].vr) masina[trcvor] = 2;
            
        }
    }
    if(duzina[end] == 500000){cout << -1;return 0;}
    cout << duzina[end];
    return 0;
}