#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

struct Ut
{
    int a;
    int b;
    int t;
};

int PathFinder(vector<Ut> Ways, bool State, set<int> NotAllowed, int Searched, int Goal) {
    int Best = Ways.size() + 1;
    int Changes;
    bool inState;

    for (int i = 0; i < Ways.size(); i++) {        
        Changes = 0;
        inState = State;

        bool in = NotAllowed.find(Ways[i].b) != NotAllowed.end();
        if (Ways[i].a == Searched && !in) {
            if (Ways[i].t != inState) {
                inState = !inState;
                Changes++;
                
                if (Changes >= Best)
                    continue;
            }
            if (Ways[i].b != Goal)
            {
                NotAllowed.insert(Searched);
                Changes += PathFinder(Ways, inState, NotAllowed, Ways[i].b, Goal);
            }                        
        }
        else
        {
            Changes = -1;
        }

        if (Changes < Best && Changes != -1)
            Best = Changes;
    }

    return Best;
}

int main()
{
    int N, M;
    cin >> N >> M;

    vector<Ut> Ways;
    Ut seged;

    int i;
    for (i = 0; i < M; i++) {
        cin >> seged.a; cin >> seged.b; cin >> seged.t;
        Ways.push_back(seged);
    }
    
    int u, v;
    cin >> u >> v;
    
    set<int> NotAllowed;
    cout << PathFinder(Ways, false, NotAllowed, u, v);
}