#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
#include <string>
#include <cstring>
#include <ctime>
#include <set>
#include <list>
#include <sstream>
#include <iomanip>
#include <map>
#include <stack>
#include <unordered_map>
#include <queue>
#include <deque>
#include <chrono>
#include <fstream>
#include <sstream>
#include <ostream>
#include <assert.h>
#include <cstdint>
#define ll long long
#define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define PI 3.14159265358979323846 
#define all(c) (c).begin(), (c).end()
using namespace std;

int n, m;
vector<vector<pair<int, int>>> a;
vector<vector<int>> dp;

const int INF = 1e9;

int check(int st, int t, vector<bool> visited) {
	if (dp[st][t] != INF) return dp[st][t];
	visited[st] = 1;
	int ans = INF;
	for (pair<int, int> p : a[st]) {
		if (visited[p.first]) continue;
		if (p.second != t) ans = min(ans,1+check(p.first, t ^ 1,visited));
		else ans = min(ans,check(p.first, t, visited));
	}
	return dp[st][t] = ans;
}

void solve() {
	cin >> n >> m;
	a = vector<vector<pair<int, int>>>(n + 1);
	dp = vector<vector<int>>(n + 1, vector<int>(2,INF));
	for (int i = 0; i < m; i++) {
		int c, b, t;
		cin >> c >> b >> t;
		a[c].push_back({ b,t });
		a[b].push_back({ c,t });
	}
	int x, y;
	cin >> x >> y;
	dp[y][0] = dp[y][1] = 0;
	check(x,0,vector<bool>(n+1,0));
	if (dp[x][0] == INF) cout << -1;
	else cout << dp[x][0];
}

int main() {
	sync;
	int t = 1;
	//cin >> t;
	while (t--) {
		solve();
	}
}