#include <bits/stdc++.h>
using namespace std;
int read() {
  int x = 0, y = 0;
  char c = getchar();
  while (c < '0' || '9' < c) c = getchar();
  while ('0' <= c && c <= '9')
    x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
  return x;
}
int n, m;
struct Matrix {
  int r, c;
  bitset<500> a[500 + 5];
  bitset<500>& operator[](int x) { return a[x]; }
  void Init(int R, int C) {
    r = R, c = C;
    for (int i = 1; i <= r; i++) a[i].reset();
    return;
  }
  friend Matrix operator*(Matrix A, Matrix B) {
    Matrix C;
    C.Init(A.r, B.c);
    for (int i = 1; i <= A.r; i++)
      for (int k = 1; k <= A.c; k++)
        if (A[i][k]) C[i] |= B[k];
    return C;
  }
} f[61 + 5][2], a, b;
int main() {
  n = read(), m = read();
  f[0][0].Init(n, n), f[0][1].Init(n, n);
  for (int i = 1; i <= m; i++) {
    int u = read(), v = read(), p = read();
    f[0][p][u][v] = 1;
  }
  for (int k = 1; k <= 61; k++) {
    f[k][0] = f[k - 1][0] * f[k - 1][1];
    f[k][1] = f[k - 1][1] * f[k - 1][0];
  }
  int opt = 0;
  long long ans = 0;
  a.Init(1, n), a[1][1] = 1;
  for (int k = 61; k >= 0; k--) {
    b = a * f[k][opt];
    if (b[1].count()) {
      a = b, opt ^= 1;
      ans += (1ll << k);
    }
    if (ans > (long long)1e18) {
      puts("-1");
      return 0;
    }
  }
  printf("%lld\n", ans);
  return 0;
}
