#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool upmin(T &x, T y) {
  return y < x ? x = y, 1 : 0;
}
template <typename T>
inline bool upmax(T &x, T y) {
  return x < y ? x = y, 1 : 0;
}
const long double eps = 1e-11;
const long double pi = acos(-1);
const int oo = 1 << 30;
const long long loo = 1ll << 60;
const int mods = 1e9 + 7;
const int MAXN = 10000005;
const int INF = 0x3f3f3f3f;
inline int read() {
  int f = 1, x = 0;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x << 3) + (x << 1) + (c ^ 48);
    c = getchar();
  }
  return x * f;
}
long long ans = 0;
bitset<505> f[65][2][505], g, Ans;
signed main() {
  int n = read(), m = read();
  for (int i = 1, u, v, c; i <= m; i++)
    u = read(), v = read(), c = read(), f[0][c][u][v] = 1;
  for (int i = 1; i <= 60; i++)
    for (int j = 0; j < 2; j++)
      for (int k = 1; k <= n; k++)
        if (f[i - 1][j][k].count())
          for (int p = 1; p <= n; p++)
            if (f[i - 1][j][k][p]) f[i][j][k] |= f[i - 1][j ^ 1][p];
  Ans[1] = 1;
  for (int i = 60, nw = 0; i >= 0; i--) {
    g = 0;
    for (int k = 1; k <= n; k++)
      if (Ans[k]) g |= f[i][nw][k];
    if (g.count()) Ans = g, ans += (1ll << i), nw ^= 1;
  }
  if (ans > 1e18)
    puts("-1");
  else
    printf("%lld\n", ans);
  return 0;
}
