#include <bits/stdc++.h>

using namespace std;

struct node {
	int v;
	int t;
};

const int N = 2e5 + 10;
int n, m;
vector<node> g[N];
int start, finish;
int dist[N];
deque<int> q;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> m;
    for(int i = 0; i < m; i++) {
    	int u, v, t;
    	cin >> u >> v >> t;
    	g[u].push_back({v, t});
    	g[v].push_back({u, t});
    }
    cin >> start >> finish;
    for(int i = 1; i <= n; i++) dist[i] = 1e9;
    dist[start] = 0;
    q.push_back(start);
    while(!q.empty()) {
    	int u = q.front();
    	q.pop_front();
    	for(node v : g[u]) {
    		int add = ((dist[u] & 1) ^ v.t);
    		if(dist[u] + add < dist[v.v]) {
    			dist[v.v] = dist[u] + add;
    			if(!add) q.push_front(v.v);
    			else q.push_back(v.v);
    		}
    	}
    }
    if(dist[finish] == 1e9) cout << -1;
    else cout << dist[finish];
    return 0;
}