#include <bits/stdc++.h>
using namespace std;
const int N = 3e7 + 10;
const int INF = 0x3f3f3f3f;
bitset<510> f[2][65][510], tmp, g;
int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    f[c][0][a][b] = 1;
  }
  for (int i = 1; i <= 60; i++) {
    for (int j = 1; j <= n; j++) {
      for (int k = 1; k <= n; k++) {
        if (f[1][i - 1][j][k] != 0) f[1][i][j] |= f[0][i - 1][k];
        if (f[0][i - 1][j][k] != 0) f[0][i][j] |= f[1][i - 1][k];
      }
    }
  }
  if (f[0][60][1].count() != 0) {
    puts("-1");
    return 0;
  }
  long long ans = 0;
  tmp[1] = 1;
  int now = 0;
  for (int i = 59; i >= 0; i--) {
    g.reset();
    for (int j = 1; j <= n; j++) {
      if (tmp[j]) g |= f[now][i][j];
    }
    if (g.count()) {
      ans += 1ll << i;
      tmp = g;
      now ^= 1;
    }
  }
  if (ans > 1e18) {
    puts("-1");
    return 0;
  }
  cout << ans;
  return 0;
}
