/**
 *    author:  wxhtzdy
 *    created: 19.11.2022 12:33:08
**/
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);  
  int n, m;
  cin >> n >> m;
  vector<vector<pair<int, int>>> g(n);
  for (int i = 0; i < m; i++) {
    int x, y, t;
    cin >> x >> y >> t;
    --x; --y;
    g[x].emplace_back(y, t);
    g[y].emplace_back(x, t);
  }
  int a, b;
  cin >> a >> b;
  --a; --b;
  const int inf = 1e9;
  vector<vector<int>> dist(n, vector<int>(2, inf));                                             
  dist[a][0] = 0;
  deque<pair<int, int>> que;
  que.emplace_back(a, 0);
  vector<vector<bool>> was(n, vector<bool>(2));
  while (!que.empty()) {
    int i = que.front().first;
    int t = que.front().second;
    que.pop_front();
    if (was[i][t]) {
      continue;
    }
    was[i][t] = true;
    for (auto& p : g[i]) {
      int to = p.first;
      int w = p.second;
      int new_d = dist[i][t] + (t != w);
      if (dist[to][w] > new_d) {
        dist[to][w] = new_d;
        if (t == w) {
          que.emplace_front(to, w);       
        } else {
          que.emplace_back(to, w);
        }
      }
    } 
  }
  int ans = min(dist[b][0], dist[b][1]);
  cout << (ans == inf ? -1 : ans) << '\n'; 
  return 0;
}