#include <bits/stdc++.h>
using namespace std;
const int CN = 510;
int read() {
  int s = 0, ne = 1;
  char c = getchar();
  for (; c < '0' || c > '9'; c = getchar())
    if (c == '-') ne = -1;
  for (; c >= '0' && c <= '9'; c = getchar()) s = (s << 1) + (s << 3) + c - '0';
  return s * ne;
}
int n, m;
bitset<CN> f[61][2][CN], s, t;
int main() {
  n = read(), m = read();
  for (int i = 1; i <= m; i++) {
    int u = read(), v = read(), tp = read();
    f[0][tp][u][v] = 1;
  }
  for (int e = 1; e <= 60; e++)
    for (int k = 1; k <= n; k++)
      for (int i = 1; i <= n; i++) {
        if (f[e - 1][0][i][k]) f[e][0][i] |= f[e - 1][1][k];
        if (f[e - 1][1][i][k]) f[e][1][i] |= f[e - 1][0][k];
      }
  s[1] = 1;
  int p = 0;
  long long ans = 0;
  for (int k = 60; k + 1; k--) {
    t.reset();
    for (int i = 1; i <= n; i++)
      if (s[i]) t |= f[k][p][i];
    if (t.any()) {
      ans += 1ll << k, s = t, p ^= 1;
    }
  }
  if (ans > (long long)1e18)
    puts("-1");
  else
    printf("%lld\n", ans);
  return 0;
}
