#include <bits/stdc++.h>
#define mp(x,y) make_pair(x,y)


using namespace std;




int main()
{
    int n,m;
    vector<vector<pair<int,int>>> graf(200005);
    priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>> pq;
    bool pos[200005][2];
    int dist[200005][2];
    scanf("%d %d",&n,&m);
    for(int i=0; i<m; i++)
    {
        int a,b,t;
        scanf("%d %d %d",&a,&b,&t);
        graf[a].push_back(mp(b,t));
        graf[b].push_back(mp(a,t));
    }
    int u,v;
    scanf("%d %d",&u,&v);
    for(int i=1; i<=n; i++)
    {
        pq.push(mp((i==u ? 0:INT_MAX),mp(i,0)));
        pq.push(mp(INT_MAX,mp(i,1)));
        dist[i][0]=INT_MAX;
        dist[i][1]=INT_MAX;
    }
    dist[u][0]=0;
    dist[u][1]=1;

    while(pq.size()>0 && !pos[v][0] && !pos[v][1])
    {
        while(pos[pq.top().second.first][pq.top().second.second])pq.pop();
        if(pq.size()==0)break;
        if(pq.top().first==INT_MAX)break;
        int ind=pq.top().second.first;
        int t1=pq.top().second.second;

        for(int i=0; i<graf[ind].size(); i++)
        {
            int node=graf[ind][i].first;
            int t=graf[ind][i].second;
            if(!pos[node][t])
            {
                if(dist[node][t]==INT_MAX || dist[ind][t1]+(t^t1) < dist[node][t])
                {
                    dist[node][t]=dist[ind][t1]+(t^t1);
                    pq.push(mp(dist[node][t],mp(node,t)));
                }
            }
        }
        pos[ind][t1]=true;
    }


    if(dist[v][0]==INT_MAX && dist[v][1]==INT_MAX)printf("-1");
    else printf("%d", min(dist[v][0],dist[v][1]));


    return 0;
}