#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) x.begin(), x.end()
#define pf push_front
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define sz(x) (int)x.size()
#define f first
#define s second
#define mod 1000000007
// const int mod = 998244353;
// OVERFLOW!!!!!!!!!!!!!!!!!!
const int maxn = 2e5 + 100;
vector<pair<int, int>> g[maxn];
vector<pair<int, int>> res(maxn, mp(1e9, 1e9));
int main()
{
   ios_base::sync_with_stdio(false);
   cout.tie(nullptr);
   cin.tie(nullptr);
   int n, m;
   cin >> n >> m;
   for (int i = 0; i < m; i++)
   {
      int a, b, c;
      cin >> a >> b >> c;
      g[a].pb({b, c});
      g[b].pb({a, c});
   }
   int start, end;
   cin >> start >> end;
   // samo 0-1 BFS?
   deque<int> dq;
   //.f je najkraci put, a .s je da znam da li je upaljen ili ugasen
   dq.push_front(start);
   res[start].f = res[start].s = 0;
   while (!dq.empty())
   {
      auto u = dq.front();
      dq.pop_front();
      for (auto e : g[u])
      {
         int v = e.f, w = e.s;
         if (res[u].s == w)
         {
            if (res[u].f < res[v].f)
            {
               res[v].f = res[u].f;
               dq.push_front(v);
               res[v].s = w;
            }
         }
         else
         {
            if (res[u].f + 1 < res[v].f)
            {
               res[v].f = res[u].f + 1;
               dq.push_back(v);
               res[v].s = w;
            }
         }
      }
   }
   if (res[end].f >= 1e9)
      cout << "-1";
   else
      cout << res[end].f;
   return 0;
}