#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>

#define ff(i,a,b) for(int (i) = (a); (i) <= (b); ++(i))
#define fb(i,a,b) for(int (i) = (a); (i) >= (b); --(i))
#define mod 998244353
#define xx first
#define yy second
#define all(a) (a).begin(), (a).end()
#define pb push_back
#define ll long long
#define pii pair<int,int>


using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>,rb_tree_tag, tree_order_statistics_node_update> ordered_set;/// find_by_order(x)(x+1th) , order_of_key() (strictly less)
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());


int n,m;
struct cvor{
    pii x;
    int w;
};

vector<cvor> graf[200005][2];
int dist[200005][2];

void bfs(int x, int st){
    ff(i,1,n){
        ff(j,0,1)dist[i][j] = 1e9;
    }
    dist[x][st] = 0;
    deque<pii> q;
    q.push_front({x,st});
    while(!q.empty()){
        pii sta = q.front();
        q.pop_front();
        for(auto c:graf[sta.xx][sta.yy]){
            pii koji = c.x;
            if(dist[sta.xx][sta.yy] + c.w < dist[koji.xx][koji.yy]){
                dist[koji.xx][koji.yy] = dist[sta.xx][sta.yy] + c.w;
                if(c.w == 1)q.push_back(koji);
                else q.push_front(koji);
            }
        }
    }
}


int main()
{

    ios_base::sync_with_stdio(false); cin.tie(0);

    cin >> n >> m;
    ff(i,1,n){
        graf[i][0].pb({{i,1},1});
        graf[i][1].pb({{i,0},1});
    }
    ff(i,1,m){
        int a,b,c;
        cin >> a >> b >> c;
        graf[a][c].pb({{b,c},0});
        graf[b][c].pb({{a,c},0});
    }
    int x,y;
    cin >> x >> y;
    bfs(x,0);
    int sta = min(dist[y][0], dist[y][1]);
    if(sta < 1e9)cout << sta << "\n";
    else cout << -1 << "\n";
    return 0;
}