#include <bits/stdc++.h>
#define ll long long
#define MAXN 200010
#define INF 2000000010

using namespace std;

int N, M, X, Y, T, A, B;
vector <vector<pair<int, int> > > graf;
vector <int> dist;
vector <int> dp;

void BFS(int cvor)
{
    int boja;
    bool prvi = true;
    dist[cvor] = 0;
    queue <int> q;
    queue <int> boje;
    q.push(cvor);
    boje.push(0);
    while(q.size())
    {
        int prosli = q.front();
        boja = boje.front();
        boje.pop();
        q.pop();
        for(auto par : graf[prosli])
        {
            int sled = par.first;
            int tren_boja = par.second;
            if(dist[sled] == -1) {dist[sled] = dist[prosli] + 1; boje.push(tren_boja); q.push(sled);}
            else continue;
            dp[sled] = min(dp[sled], dp[prosli] + !(tren_boja == boja));
            ///cerr << "Prosli: " << prosli << " | " << "Trenutni: " << sled << " | " << "Boja: " << boja << " | " << "Tren boja: " << tren_boja <<" | dp[sled]:  "<< dp[sled] << endl;
        }
    }
}

int main()
{
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> N >> M;
    dist.resize(N + 5, -1);
    dp.resize(N + 5, INF);
    graf.resize(N + 5);
    for(int i = 0; i < M; i++)
    {
        cin >> X >> Y >> T;
        graf[X].push_back({Y, T});
        graf[Y].push_back({X, T});
    }
    cin >> A >> B;
    dp[A] = 0;
    BFS(A);
    if(dp[B] == INF) cout << -1 << endl;
    else cout << dp[B] << endl;
    return 0;
}
/*
9
12
1 2 0
1 4 1
2 7 0
2 6 1
7 6 1
6 5 1
5 4 1
5 8 0
3 6 0
3 5 1
7 9 1
9 5 0
*/
/**
42 55
1 3 1
1 2 0
2 3 1
4 3 0
1 4 0
4 5 0
1 5 0
1 6 1
1 7 0
1 8 1
4 17 1
5 16 1
6 15 0
7 13 0
13 14 1
13 12 1
12 11 1
8 11 1
8 10 1
8 9 0
9 18 1
9 21 0
10 21 1
10 22 0
11 22 0
22 23 1
22 24 1
21 23 1
24 37 0
37 36 1
23 36 0
36 35 0
34 35 1
35 31 0
31 32 1
31 39 1
39 38 0
39 40 1
40 23 0
40 41 0
41 42 1
42 19 0
19 18 1
18 20 0
15 16 1
15 25 1
25 26 0
26 33 0
33 32 0
31 30 0
30 29 1
29 28 1
29 27 1
27 28 0
27 16 0
1 31
**/