#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const long long INF = 1e18;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
int n, m, now;
bitset<N> f[2][70][N], g, tmp;
long long ans, fac[N];
int main() {
  n = read();
  m = read();
  for (int i = 1, u, v, w; i <= m; i++) {
    u = read();
    v = read();
    w = read();
    f[w][0][u][v] = 1;
  }
  for (int i = 1; i <= 60; i++)
    for (int u = 1; u <= n; u++)
      for (int v = 1; v <= n; v++) {
        if (f[0][i - 1][u][v] != 0) f[0][i][u] |= f[1][i - 1][v];
        if (f[1][i - 1][u][v] != 0) f[1][i][u] |= f[0][i - 1][v];
      }
  if (f[0][60][1].count()) {
    puts("-1");
    return 0;
  }
  fac[0] = 1;
  for (int i = 1; i <= 60; i++) fac[i] = fac[i - 1] * 2;
  now = 0;
  tmp[1] = 1;
  for (int i = 60; i >= 0; i--) {
    g.reset();
    for (int j = 1; j <= n; j++)
      if (tmp[j]) g |= f[now][i][j];
    if (g.count() != 0) {
      now ^= 1;
      tmp = g;
      ans += fac[i];
    }
  }
  if (ans > INF)
    puts("-1");
  else
    printf("%lld\n", ans);
  return 0;
}
