#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int sum = 0;
  char c = getchar();
  bool f = 0;
  while (c < '0' || c > '9') {
    if (c == '-') f = 1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    sum = sum * 10 + c - '0';
    c = getchar();
  }
  if (f) return -sum;
  return sum;
}
int n, m;
bitset<505> f[61][2][505], rch, ch;
const long long orz = 1000000000000000000LL;
int main() {
  int i, j, k, t, z, x, y;
  n = read();
  m = read();
  for (i = 1; i <= m; i++)
    x = read(), y = read(), k = read(), f[0][k][x][y] = 1;
  for (i = 1; i <= 60; i++)
    for (k = 1; k <= n; k++)
      for (j = 1; j <= n; j++)
        for (z = 0; z <= 1; z++)
          if (f[i - 1][z][j][k]) f[i][z][j] |= f[i - 1][z ^ 1][k];
  for (i = 1; i <= n; i++)
    if (f[60][0][1][i]) {
      puts("-1");
      return 0;
    }
  long long ans = 0;
  bool s = 0;
  for (rch[1] = 1, i = 59; i >= 0; i--) {
    for (ch = 0, j = 1; j <= n; j++)
      if (rch[j]) ch |= f[i][s][j];
    if (ch.count()) rch = ch, ans += (1LL << i), s ^= 1;
  }
  if (ans > orz)
    puts("-1");
  else
    cout << ans;
  return 0;
}
