#include<bits/stdc++.h>


using namespace std;

struct tacka {
    int p;
    bool t;
};

vector<vector<tacka> > adj;
vector<bool> vis;
priority_queue<int, vector<int>, greater<int> > p;
int u, v;

void add_edge(int a, int b, bool t) {
    tacka x;
    x.p = b;
    x.t = t;
    adj[a].push_back(x);
    x.p = a;
    adj[b].push_back(x);
}



void dfs(int x, bool prosli, int ans){
	vis[x]=1;
	int i;
	for(i = 0; i < adj[x].size(); i++){
		if(!vis[adj[x][i].p]) {
            if(prosli != adj[x][i].t){
                int y = ans + 1;
                dfs(adj[x][i].p, adj[x][i].t, y);
            }

            else
                dfs(adj[x][i].p, adj[x][i].t, ans);
		}
        else if(adj[x][i].p == v) {
            int y = ans;
            if(prosli != adj[x][i].t)
                y++;
            p.push(y);
        }
	}
}

int main() {
    int n, m;
    cin >> n >> m;
    adj.resize(n);
    for(int i = 0; i < m; i++){
        int a, b, t;
        cin >> a >> b >> t;
        a--;
        b--;
        add_edge(a, b, t);
    }
    int u1, v1;
    cin >> u1 >> v1;
    u1--;
    v1--;
    u = u1;
    v = v1;
    vis = vector<bool>(n, 0);
    vis[v] = 1;
    int ans(0);
    bool prosli = 0;
    dfs(u, prosli, ans);
    if(p.size() != 0)
        cout<<p.top();
    else
        cout << -1;




    return 0;
}