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

int main()
{

  int cv,N,M,u,v,br=0,lp;

  printf("Unesi broj santi: ");
  scanf("%d", &N);
  printf("Unesi broj puteva izmedju santi: ");
  scanf("%d", &M);

  printf("\nUnesi broj sante A, broj sante B, tip puta :\n");
int a[M],b[M],t[M];

 for(int i=0;i<M;i++)
    {
    scanf(" %d", &a[i]);
    scanf(" %d", &b[i]);
    scanf(" %d", &t[i]);
        }


do{
fflush(stdin);
    printf("Broj sante od Mike i od Laze(redom):\n");
    scanf("%d%d", &u,&v);
}while(0>u || u>N || 0>v || v>N);



lp=0;
int i=0;
do
{
    if(br>0)
        goto bout;
    if(a[i]==u)
    {

      if(lp!=t[i])
      {
          br++;
      }
       lp=t[i];
       cv=b[i];

       goto out;
    }
bout:;
    if(a[i]==cv)
    {
        if(lp!=t[i])
      {
          br++;
      }
       lp=t[i];
        cv=b[i];

        if(cv==v)
        {
            printf("\n%d", br);
            return 0;
        }
        goto out;
    }

    out:;
i++;

}while(cv!=0);

 printf("\n-1");
    return 0;
}