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

int main(){
      int n, m;
      scanf("%d", &n);
      scanf("%d", &m);

      vector<pair<int, int>> np[n];

      int a, b, w;
      for(int i = 0;i < m;i++){
            scanf("%d %d %d", &a, &b, &w);
            np[a-1].push_back({b-1, w});
      }

      scanf("%d %d", &a, &b); //a - Mika
                              //b - Laza
      a--; b--;
      w = 0; //state of the machine 

      priority_queue<pair<int, int>> close_icebergs;
      bool visited[n];
      int mchanges[n];

      for(int i = 0;i < n;i++){
            visited[i] = false;
            mchanges[i] = -1;
      }

      mchanges[a] = 0;
      close_icebergs.push({0, a});

      int k, x, y;

      while(!close_icebergs.empty()){
            k = close_icebergs.top().second;
            close_icebergs.pop();

            if(visited[k])
                  continue;
            
            visited[k] = true;

            for(auto itr: np[k]){
                  x = itr.first;
                  y = itr.second; // y = 0 | 1
                                  // w = 0 | 1 else mchanges[x]++
                  if(mchanges[k] % 2 == y)
                        mchanges[x] = mchanges[k];
                  else
                        mchanges[x] = mchanges[k] + 1;

                  close_icebergs.push({-mchanges[x], x});
            }
      }

      printf("%d\n", mchanges[b]);
      return 0;
}