#include <iostream>
#include <queue>
#include <vector>

using namespace std;

//if(cvor<=n) cvor = n , stanje = 0;
//if(cvor>=n) cvor = cvor-n , stanje = 1;

bool prov[410000];
int min_rastojanje[410000];
vector< pair<int, bool> > grane[210000];

int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);

  int n, m, a, b, i;
  bool t;
  int _od, _do;
  priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;

  cin >> n >> m;

  for (i = 0; i < m; i++) {

    cin >> a >> b >> t;
  
    pair<int, bool> grana;
    grana.first = b;
    grana.second = t;

    grane[a].push_back(grana);

    grana.first = a;
    grana.second = t;

    grane[b].push_back(grana);

  }

  cin >> _od >> _do;

  pair<int, int> par1, par2;
  pair<int, bool> grana;

  for (i = 0; i <= n; i++) {

    prov[i] = false;
    prov[i + n] = false;

    min_rastojanje[i] = -1;
    min_rastojanje[i + n] = -1;

  }

  par1.first = 0;
  par1.second = _od;

  pq.push(par1);
  min_rastojanje[_od] = 0;

  //par1.first = udaljenost
  //par1.second = cvor 

  while(!pq.empty()){
  
    par1 = pq.top();
    pq.pop();

    int cvor,cvor_og, duzina;
    bool stanje;

    duzina = par1.first;
    cvor = par1.second;

    if (cvor > n) {
      cvor_og = cvor - n;
      stanje = 1;
    }
    else {
      cvor_og = cvor;
      stanje = 0;
    }

    if (prov[cvor] == false) {

      prov[cvor] = true;
      int am = grane[cvor_og].size();

      for (i = 0; i < am; i++) {

        grana = grane[cvor_og][i];

        int cvor2_og = grana.first;
        bool tt = grana.second;

        int cvor2;

        if (tt == 1)
          cvor2 = cvor2_og + n;
        else
          cvor2 = cvor2_og;

        int duzina_rn = duzina;

        if ((tt == 1 && stanje == 0) || (tt == 0 && stanje == 1))
          duzina_rn++;

        if (prov[cvor2] == false && (duzina_rn < min_rastojanje[cvor2] || min_rastojanje[cvor2] == -1)) {

          min_rastojanje[cvor2] = duzina_rn;

          par2.first = duzina_rn;
          par2.second = cvor2;

          pq.push(par2);

        }


      }


    }


  }

  int u1 = min_rastojanje[_do];
  int u2 = min_rastojanje[_do + n];

  /*
  for (i = 1; i <= n; i++) {

    cout << i << " : " << min_rastojanje[i] << " " << min_rastojanje[i + n] << '\n';

  }
  */

  if (u1 == -1 && u2 == -1) {
    cout << -1 << '\n';
    return 0;
  }

  if (u1 == -1) {
    cout << u2 << '\n';
    return 0;
  }
      
  if (u2 == -1) {
    cout << u1 << '\n';
    return 0;
  }

  cout << min(u1, u2) << '\n';

  return 0;

}