#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
// grci se
vector <int> adj[10000];
vector <int> v[10000];
int pathnum=0;
int k=0;
void dfsutil(int u, int d, bool visited[], int path[], int& pathind)
{
    visited[u] = true;
    path[pathind] = u;
    pathind++;
    if(u==d)
    {
        for(int i=0;i<pathind;++i) {
            v[k].push_back(path[i]);
        }
        k++;
        pathnum++;
    }
    else
    {
        vector<int> ::iterator i;
        for(i=adj[u].begin(); i!=adj[u].end(); ++i)
        {
            if(!visited[*i])
                dfsutil(*i, d, visited, path, pathind);
        }
    }
    pathind--;
    visited[u] = false;
}

void dfs(int s, int d)
{
    bool visited[10000];
    memset(visited, 0, sizeof(visited));
    int path[10000];
    int pathind = 0;
    dfsutil(s, d, visited, path, pathind);
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    int x, y, s;
    int start, dest;
    int states[10000], c;
    int j=0;
    cin >> n >> m;
    map<pair<int, int>, int> mp;
    for(int i=0;i<m;++i)
    {
        cin >> x >> y >> s;
        adj[x].push_back(y);
        adj[y].push_back(x);
        mp[{x, y}] = s;
    }
    cin >> start >> dest;
    dfs(start, dest);
    int curstate;
    if(v[0].size()==0) {
        cout << -1;
    }
    else
    {
        for(int i=0;i<pathnum;++i)
        {
            c = 0;
            curstate = 0;
            for(auto it = v[i].begin(); it!= v[i].end()-1; it++)
            {
                if(mp[{*it, *(it+1)}] != curstate)
                    {
                        if(curstate>0) {
                            curstate--;
                            c++;
                        }
                        else {
                            curstate++;
                            c++;
                        }
                    }
            }
            states[j++] = c;
        }
        int ans = *min_element(states, states+pathnum);
        cout << ans;
    }
    return 0;
}