#include <bits/stdc++.h>
using namespace std;
const int N = 4e5 + 228;
const int K = 502;
bitset<K> to[64][K][2];
int main() {
  ios::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int x, y, t;
    cin >> x >> y >> t;
    x--;
    y--;
    to[0][x][t][y] = 1;
  }
  for (int st = 1; st <= 60; st++) {
    for (int v = 0; v < n; v++) {
      for (int j = 0; j < n; j++) {
        to[st][v][0][j] = 0;
      }
      for (int j = 0; j < n; j++) {
        if (to[st - 1][v][0][j] == 1) to[st][v][0] |= to[st - 1][j][1];
      }
      for (int j = 0; j < n; j++) {
        to[st][v][1][j] = 0;
      }
      for (int j = 0; j < n; j++) {
        if (to[st - 1][v][1][j] == 1) to[st][v][1] |= to[st - 1][j][0];
      }
    }
  }
  for (int i = 0; i < n; i++) {
    if (to[60][i][0].count() != 0) {
      cout << -1 << "\n";
      return 0;
    }
  }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    bitset<K> cur, temp;
    long long len = 0;
    for (int j = 0; j < n; j++) {
      cur[j] = 0;
    }
    cur[i] = 1;
    bool fl = 0;
    for (int st = 60; st >= 0; st--) {
      for (int j = 0; j < n; j++) {
        temp[j] = 0;
      }
      for (int j = 0; j < n; j++) {
        if (!cur[j]) continue;
        temp |= to[st][j][fl];
      }
      if (temp.count() == 0) continue;
      cur = temp;
      len += (1LL << (long long)st);
      fl ^= 1;
    }
    ans = max(ans, len);
  }
  if (ans > (long long)1e18) {
    cout << "-1\n";
  } else {
    cout << ans << "\n";
  }
  return 0;
}
