#include <iostream>
#include <unordered_map>
#include <cmath>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
#include <queue>

int main() {
    std::ios_base::sync_with_stdio(false); std::cin.tie(0);
    
    int n, k;
    std::cin >> n >> k;
    //                  node                     node state
    std::unordered_map<int, std::vector<std::pair<int, int>>> r;
    for (int i = 0; i < k; i++) {
        int a, b, c;
        std::cin >> a >> b >> c;

        r[a].push_back({ b, c });
        r[b].push_back({ a, c });
    }
    //                 node           min state
    std::unordered_map<int, std::pair<int, int>> res;

    //                  node            min state
    std::queue<std::pair<int, std::pair<int, int>>> q;

    int u, v;

    std::cin >> u >> v;

    int result = 532532532;

    q.push({ u, {1, 0} });
    while (!q.empty()) {
        int node = q.front().first;
        int min = q.front().second.first;
        int state = q.front().second.second;
        if (node == v) {
            if (min < result) {
                result = min;
            }
        }
        q.pop();
        for (int i = 0; i < r[node].size(); i++) {
            std::pair<int, int> child = r[node][i];
            int newDistance = min + (child.second != state);
            if (res[child.first].first > newDistance || res[child.first].first == 0) {
                res[child.first] = { newDistance, child.second };
                q.push({ child.first, { newDistance, child.second } });
            }
        }
    }

    std::cout << result-1 << std::endl;
}