#include <iostream>
#include <vector>
#include <string>
#include<algorithm>
#include<stack>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    stack<int> s;
    bool a[200000], b[200000];
    int n, m, i, j, k, o, p;
    cin >> n;
    cin >> m;
    vector<vector<int>> voda(n);
    vector<vector<int>> led(n);
    bool t;
    for (i = 0; i < n; i++)
    {
        a[i] = false;
        b[i] = false;
    }
    for (i = 0; i < m; i++)
    {
        cin >> o >> p>>t;
        if (t == 0) {
            voda[o-1].push_back(p-1);
            voda[p-1].push_back(o-1);
        }
        else
        {
            led[o-1].push_back(p-1);
            led[p-1].push_back(o-1);
        }
        }
    cin >> k;
    k--;
    s.push(k);
    int z;
    cin >> z;
    z--;
    bool zavr = false;
    int promena=0;
    int rezult = -1;
    bool stigo = false;
    stack <int>sante;
    sante.push(k);
    while ((!sante.empty() || !s.empty())&&stigo==false)
    {
        while (!s.empty())
        {
            k = s.top();
            s.pop();
            if (a[k] == false)
            {

                a[k] = true;
                while (!voda[k].empty())
                {
                    s.push(voda[k][voda[k].size()-1]);
                    sante.push(voda[k][voda[k].size() - 1]);
                    if (voda[k][voda[k].size() - 1] == z && stigo == false)
                    {
                        rezult = promena;
                        stigo = true;
                    }
                    voda[k].pop_back();
                   

                }


            }

        }
        promena++;
        while (!sante.empty())
        {
            k = sante.top();
            sante.pop();
            if (b[k] == false)
            {

                b[k] = true;
                //cout << k;
                //for (i = 0; i < v[k].size(); i++)
                while (!led[k].empty())
                {
                    s.push(led[k][led[k].size()-1]);
                    sante.push(led[k][led[k].size() - 1]);
                    if (led[k][led[k].size() - 1] == z && stigo == false)
                    {
                        rezult = promena;
                        stigo = true;
                    }
                    led[k].pop_back();
                    

                }


            }

        }
        promena++;
    }
    cout << rezult;
}