#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

int main(void)
{
	int	N = 0,
					M = 0,
					U = 0,
					V = 0,
					promena = 0,
					promenat = 0,
					a = 0,
					b = 0,
					i, j, k, c = 0,
					p = 1,
					r = 0;
	int masina = 0;
	struct put* putevi = NULL;
	struct put* put = NULL;
	
	scanf("%d %d", &N, &M);
	putevi = malloc(M * sizeof(struct put));
	for(i = 0; i < M; i++)
	{
		put = &putevi[i];
		scanf("%d %d %d", &(put->a), &(put->b), &(put->t));
	}
	scanf("%d %d", &U, &V);
	
	for(i = 0; i < M; i++)
	{
		put = &putevi[i];
		if(put->a == U)
		{
			b = put->b;
			if(put->t != masina)
			{
				promenat++;
				masina = put->t;
			}
			for(j = 0; j < M; j++)
			{
				put = &putevi[j];
				if(put->a == b)
				{
					a = put->a;
					b = put->b;
					if(put->t != masina)
					{
						promenat++;
						masina = put->t;
					}
					if(b == V)
					{
						r = 1;
						break;
					}
					j = 0;
				}
				else
					if(j == M - 1)
					{
						c++;
						masina = !masina;
						for(k = 0; k < M; k++)
							if(putevi[k].b == b)
							{
								if(putevi[k].t == masina)
								{
									promenat--;
								}
								a = putevi[k].a;
								putevi[k].a = 0;
								putevi[k].b = 0;
								putevi[k].t = 0;
								break;
							}
						
						b = a;
						j = 0;
						if(c > M)
							break;
					}
			}
			if(p && promenat != 0)
			{
				promena = promenat;
				p = 0;
			}
			if(promenat < promena)
				promena = promenat;
		}
	}
	
	if(!r)
		promena = -1;
	
	printf("%d", promena);
	
	free(putevi);
	
	return 0;
}