#include <bits/stdc++.h>
using namespace std;
inline int read() {
  char c = getchar();
  int x = 0;
  bool f = 0;
  for (; !isdigit(c); c = getchar()) f ^= !(c ^ 45);
  for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
  if (f) x = -x;
  return x;
}
int n, m;
bitset<505> f[2][63][505], t, now;
signed main() {
  n = read(), m = read();
  for (register int i = (1); i <= (m); ++i) {
    int u = read(), v = read(), w = read();
    f[w][0][u][v] = 1;
  }
  for (register int i = (0); i <= (59); ++i)
    for (register int u = (1); u <= (n); ++u)
      for (register int v = (1); v <= (n); ++v) {
        if (f[0][i][u][v]) f[0][i + 1][u] |= f[1][i][v];
        if (f[1][i][u][v]) f[1][i + 1][u] |= f[0][i][v];
      }
  if (f[0][60][1].count()) return puts("-1") & 0;
  long long res = 0, lim = 1e18;
  int cur = 0;
  t[1] = 1;
  for (register int i = (60); i >= (0); --i) {
    now.reset();
    for (register int j = (1); j <= (n); ++j)
      if (t[j]) now |= f[cur][i][j];
    if (now.count()) {
      cur ^= 1, res += (1ll << i), t = now;
      if (res > lim) {
        puts("-1");
        return 0;
      }
    }
  }
  cout << res;
  return 0;
}
