#include <bits/stdc++.h>

using namespace std;
long long int typedef li;

vector<int> g[2][200003];
int dub[2][200003];
bool vis[2][200003];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    
    int n,m; cin>>n>>m;
    while (m--)
    {
        int u,v,w; cin>>u>>v>>w;
        g[w][u].push_back(v);
        g[w][v].push_back(u);
    }

    int s,t; cin>>s>>t;
    list<pair<int,pair<bool,int>>> bfs;
    bfs.push_back({0,{0,s}});

    while (!bfs.empty())
    {
        int d=bfs.front().first;
        bool masina=bfs.front().second.first;
        int p=bfs.front().second.second;
        bfs.pop_front();

        if (vis[masina][p]) continue;
        vis[masina][p]=1,dub[masina][p]=d;

        bfs.push_back({d+1,{!masina,p}});
        for (auto it : g[masina][p]) bfs.push_front({d,{masina,it}});
    }

    if (!vis[0][t] && !vis[1][t]) return cout<<-1,0;
    cout<<min(dub[0][t],dub[1][t])<<endl;
}