#include <bits/stdc++.h>
#include <iostream>
#include <limits.h>
using namespace std;


static int graf[200001][200001] = {0};
int n;
int nkraciput[200001];
int stanje[200001];
bool poseceno[200001];

int najmanji(int nkraciput[], bool poseceno[]) {
	int min = INT_MAX, index;
	for (int i = 0; i < n; ++i)
	{
		if (!poseceno[i] && nkraciput[i] < min) {
			min = nkraciput[i];
			index = i;
		}
	}
	return index;
}

void dijkstra(int pocetak, int kraj) {
	
	for (int i = 0; i < n; ++i)
	{
		nkraciput[i] = INT_MAX;
	}
	nkraciput[pocetak] = 0;
	stanje[pocetak] = 0;
	int u; 
	while (u != kraj) {
		u = najmanji(nkraciput, poseceno);

		for (int i = 0; i < n; ++i) {
			if (poseceno[i])
				continue;

			if (graf[u][i] > 0) {
				int veza = graf[u][i] - 1;
				if (stanje[u] == veza) {
					if (nkraciput[i] > nkraciput[u]) {
						nkraciput[i] = nkraciput[u];
						stanje[i] = stanje[u];
					}
				}
				else {
					if (nkraciput[i] > nkraciput[u]+1) {
						nkraciput[i] = nkraciput[u]+1;
						stanje[i] = (stanje[u] + 1) % 2; 
					}
				}
			}
		}
		poseceno[u] = true;
		}
	if (nkraciput[kraj] == INT_MAX)
		cout << -1;
	else
		cout << nkraciput[kraj];
	}
int main()
{
	int m;
	int a, b, t;
	int u, v;
	cin >> n >> m;
	for (int i = 0; i < m; ++i)
	{
		cin >> a >> b >> t;
		graf[a-1][b-1] = t+1;
		graf[b-1][a-1] = t+1;
	}
	cin >> u >> v;


	dijkstra(u-1, v-1);

	return 0;
}