#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define sp ' '
#define en '\n'
#define smin(a, b) a = min(a, b)
#define smax(a, b) a = max(a, b)
using namespace std;
const int N = 2e5 + 2;
const int inf = 2e9;
struct Dsu {
    int link[N], sz[N];
    void Init(int n) {
        for (int i = 0; i < n; i++) {
            link[i] = i;
            sz[i] = 1;
        }
    }
    int Find(int x) {
        if (x == link[x]) return x;
        return link[x] = Find(link[x]);
    }
    void Unite(int u, int v) {
        u = Find(u); v = Find(v);
        if (u == v) return;
        link[v] = u;
        sz[u] += sz[v];
    }
    int Size(int u) {
        u = Find(u);
        return sz[u];
    }
}d[2];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, m;
    cin >> n >> m;
    vector<array<int, 3>> e(m);
    for (int i = 0; i < m; i++) {
        cin >> e[i][0] >> e[i][1] >> e[i][2];
        e[i][0] -= 1; e[i][1] -= 1;
    }
    d[0].Init(n); d[1].Init(n);
    for (int i = 0; i < m; i++) {
        d[e[i][2]].Unite(e[i][0], e[i][1]);
    }
    vector<int> idx(n, -1), idy(n, -1);
    int tsz = 0;
    for (int i = 0; i < n; i++) {
        if (idx[d[0].Find(i)] == -1) idx[d[0].Find(i)] = tsz++;
        if (idy[d[1].Find(i)] == -1) idy[d[1].Find(i)] = tsz++;
    }
    for (int i = 0; i < n; i++) {
        idx[i] = idx[d[0].Find(i)];
        idy[i] = idy[d[1].Find(i)];
    }
    vector<vector<int>> g(tsz);
    for (int i = 0; i < n; i++) {
        if (d[0].Size(i) > 1 && d[1].Size(i) > 1) {
            g[idx[i]].push_back(idy[i]);
            g[idy[i]].push_back(idx[i]);
        }
    }
    int od; cin >> od; od -= 1;
    queue<int> q;
    vector<int> dist(tsz, inf);
    dist[idx[od]] = 0; dist[idy[od]] = 1;
    q.push(idx[od]); q.push(idy[od]);
    while (!q.empty()) {
        int s = q.front();
        q.pop();
        for (int u : g[s]) {
            if (dist[s] + 1 < dist[u]) {
                dist[u] = dist[s] + 1;
                q.push(u);
            }
        }
    }
    int gde; cin >> gde; gde -= 1;
    cout << min(dist[idx[gde]], dist[idy[gde]]) << en;
    return 0;
}