#include<bits/stdc++.h>
using namespace std;
int N,M,mink[200009][4],u,v,kk,stanje0,stanje1;
struct slog1{
  int a,b,stanje;
}S1;
struct slog2{
  int id,stanje,k;
  bool operator<(const slog2 &a)const{
    return k>a.k;
  }
}S2,S22;
vector<slog1>graf[200009];
priority_queue<slog2>PQ;
int Bfs(int u,int v){
  for(int i=0; i<=N+3; i++)mink[i][1]=mink[i][0]=1e9;
  mink[u][0]=0;
  mink[u][1]=1;
  S2.id=u;
  S2.k=0;
  S2.stanje=0;
  PQ.push(S2);
  S2.k=1;
  S2.stanje=1;
  PQ.push(S2);
  while(PQ.size()){
    S2=PQ.top();
    PQ.pop();
    for(int i=0; i<graf[S2.id].size(); i++){
      S1=graf[S2.id][i];
      kk=S2.k;
      if(S2.stanje!=S1.stanje)kk++;
      stanje0=0;
      stanje1=1;
      if(S1.stanje==1)swap(stanje0,stanje1);
      S22.id=S1.b;
      if(mink[S1.b][stanje0]>kk){
        S22.stanje=stanje0;
        S22.k=kk;
        mink[S1.b][stanje0]=kk;
        PQ.push(S22);
      }
      if(mink[S1.b][stanje1]>kk+1){
        S22.stanje=stanje1;
        S22.k=kk+1;
        mink[S1.b][stanje1]=kk;
        PQ.push(S22);
      }
    }
  }
  if(min(mink[v][0],mink[v][1])==1e9)return -1;
  return min(mink[v][0],mink[v][1]);
}
int main(){
  cin>>N>>M;
  for(int i=1; i<=M; i++){
    cin>>S1.a>>S1.b>>S1.stanje;
    graf[S1.a].push_back(S1);
    swap(S1.a,S1.b);
    graf[S1.a].push_back(S1);
  }
  cin>>u>>v;
  cout<<Bfs(u,v)<<endl;
  return 0;
}