#include <bits/stdc++.h>
#define ll long long

using namespace std;

typedef pair<int, int> Pair;

const int INF = 1000000001;

int main()
{
  ios_base::sync_with_stdio(false);

  int N, M;
  cin >> N >> M;

  vector<vector<pair<int, int>>> graph(N + 1);

  for (int i = 0; i < M; i++)
  {
    int a, b, t;
    cin >> a >> b >> t;
    graph[a].emplace_back(b, t);
  }

  int start, end;
  cin >> start >> end;

  vector<int> changes(N + 1, INF);
  vector<bool> done(N + 1, false);

  changes[start] = 0;

  priority_queue<Pair, vector<Pair>, greater<Pair>> pq;

  pq.emplace(0, start);

  while (!pq.empty())
  {
    int node, n;
    tie(n, node) = pq.top();
    pq.pop();

    if (done[node])
      continue;
    done[node] = true;

    if (node == end)
      break;

    for (const auto &p : graph[node])
    {
      int nextNode, m;
      tie(nextNode, m) = p;

      int newChanges = n + (m != (n % 2));
      if (!done[nextNode] && (newChanges < changes[nextNode]))
      {
        changes[nextNode] = newChanges;
        pq.emplace(newChanges, nextNode);
      }
    }
  }

  if (changes[end] < INF)
  {
    cout << changes[end] << "\n";
  }
  else
  {
    cout << "-1\n";
  }
}