#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n, m, u, v, w, c;
bitset<N> f[65][2][N], p, tmp;
long long ans;
int main() {
  scanf("%d%d", &n, &m);
  bool fl = 0;
  for (int i = (1); i <= (m); ++i)
    scanf("%d%d%d", &u, &v, &w), f[0][w][u][v] = 1;
  for (int i = (1); i <= (60); ++i) {
    for (int j = (1); j <= (n); ++j)
      for (int k = (1); k <= (n); ++k) {
        if (f[i - 1][0][j][k]) f[i][0][j] |= f[i - 1][1][k];
        if (f[i - 1][1][j][k]) f[i][1][j] |= f[i - 1][0][k];
      }
  }
  if (f[60][0][1].count()) return puts("-1"), 0;
  p[1] = 1;
  c = 0;
  for (int i = (59); i >= (0); --i) {
    tmp = 0;
    for (int j = (1); j <= (n); ++j)
      if (p[j]) tmp |= f[i][c][j];
    if (tmp.count()) {
      ans += 1ll << i;
      if (ans > 1e18) return puts("-1"), 0;
      p = tmp;
      c ^= 1;
    }
  }
  printf("%lld\n", ans);
  return 0;
}
