#include <iostream>
#include "vector"
#include "algorithm"
#include "numeric"
#include "climits"
#include "iomanip"
#include "bitset"
#include "cmath"
#include "map"
#include "deque"
#include "array"
#include "set"
#include "queue"
#define all(x) x.begin(), x.end()
using namespace std;
vector<vector<pair<int, int>>> g;
vector<int> dst;
void bfs(int v) {
    queue<pair<int, int>> a1, a0;
    a0.push({v, 0});
    while (!a0.empty() or !a1.empty()) {
        int u, ds;
        if (!a0.empty()) {
            u = a0.front().first;
            ds = a0.front().second;
            a0.pop();
        } else {
            u = a1.front().first;
            ds = a1.front().second;
            a1.pop();
        }
        if (dst[u] != -1)
            continue;
        dst[u] = ds;
        //cout << u << '\n';
        for (auto i : g[u]) {
            if (i.second == 1)
                a1.push({i.first, ds + 1});
            else
                a0.push({i.first, ds});
        }
    }
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int n, m;
    cin >> n >> m;
    dst.assign(n * 2, -1);
    g.assign(n * 2, {});
    for (int i = 0; i < m; ++i) {
        int a, b, c;
        cin >> a >> b >> c;
        a--;b--;
        if (c == 1) {
            g[a + n].push_back({b + n, 0});
            g[b + n].push_back({a + n, 0});
        } else {
            g[a].push_back({b, 0});
            g[b].push_back({a, 0});
        }
    }
    for (int i = 0; i < n; ++i) {
        g[i].push_back({i + n, 1});
        g[i + n].push_back({i, 1});
    }
    int a, b;
    cin >> a >> b;
    a--;b--;
    bfs(a);
    cout << min(dst[b], dst[b + n]) << '\n';
}