#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

int main()
{
    int n, m, u, v;

    scanf("%d%d", &n, &m);

    vector<int> adj[20001];
    vector<int> tip[20001];
    vector<int>posecen;

    for(int i = 0; i <= n; i++)
    {
        posecen.push_back(0);
        //tip[i].push_back(0);
    }


    for(int i = 0; i < m; i++)
    {
        int a, b, t;
        scanf("%d%d%d", &a, &b, &t);
        adj[b].push_back(a);
        tip[b].push_back(t);
        adj[a].push_back(b);
        tip[a].push_back(t);
    }

    scanf("%d%d", &u, &v);

    queue<int> redIsti;

    queue<int> redNovi;
    queue<int> dist;

    redNovi.push(u);
    dist.push(0);
    posecen[u] = 1;

    int state = 0;//1 nema leda, -1 ima leda
    int ctrl = 1;

    while(!redNovi.empty() && ctrl)
    {
        redIsti.push(redNovi.front());
        int currDist = dist.front();
        redNovi.pop();
        dist.pop();

        while(!redIsti.empty() && ctrl)
        {

            int x = redIsti.front();

            state = currDist%2;

            if(x == v)
            {
                printf("%d", currDist);
                ctrl = 0;
            }

            for(int i = 0; i < adj[x].size() && ctrl; i++)
            {
                int y = adj[x][i];

                if(posecen[y] == 0)
                {
                    posecen[y] = 1;
                    if(state == tip[x][i])
                    {
                        redIsti.push(y);
                        //printf("Iste boje: %d %d\n", x, y);
                    }

                    if(state != tip[x][i])
                    {
                        redNovi.push(y);
                        dist.push(currDist+1);
                        //printf("Razlicite boje: %d %d jer tip = %d a state = %d, inace currDist = %d\n", x, y, tip[x][i], state, currDist);
                    }
                }

            }
            redIsti.pop();
        }
    }

    if(ctrl)
        printf("-1");

    return 0;
}