#include <bits/stdc++.h>
using namespace std;
int n, m;
bitset<555> f[2][66][555], pre, now;
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; ++i) {
    int u, v, w;
    scanf("%d%d%d", &u, &v, &w);
    f[w][0][u][v] = 1;
  }
  for (int i = 1; i <= 60; ++i)
    for (int z = 0; z <= 1; ++z)
      for (int x = 1; x <= n; ++x)
        for (int y = 1; y <= n; ++y) {
          if (f[z][i - 1][x][y]) f[z][i][x] |= f[z ^ 1][i - 1][y];
        }
  long long ans = 0, z = 0;
  pre[1] = 1;
  for (int i = 60; i >= 0; --i) {
    now.reset();
    for (int j = 1; j <= n; ++j)
      if (pre[j]) now |= f[z][i][j];
    if (now.count()) z ^= 1, ans ^= 1ll << i, pre = now;
  }
  printf("%lld\n", ans > 1e18 ? -1 : ans);
}
