#include <bits/stdc++.h>
using namespace std;
bitset<501> dp[61][2][501], pre, cur;
int n, m;
int main() {
  cin >> n >> m;
  while (m--) {
    int u, v, w;
    cin >> u >> v >> w;
    dp[0][w][u][v] = 1;
  }
  for (int i = 1; i <= 60; i++) {
    for (int w = 0; w < 2; w++) {
      for (int x = 1; x <= n; x++) {
        for (int y = 1; y <= n; y++) {
          if (dp[i - 1][w][x][y]) {
            dp[i][w][x] |= dp[i - 1][w ^ 1][y];
          }
        }
      }
    }
  }
  long long ans = 0, w = 0;
  pre[1] = 1;
  for (int i = 60; i >= 0; i--) {
    cur.reset();
    for (int j = 1; j <= n; j++) {
      if (pre[j]) cur |= dp[i][w][j];
    }
    if (cur.count()) {
      ans |= (1LL << i);
      pre = cur;
      w ^= 1;
    }
  }
  if (ans <= 1e18)
    cout << ans;
  else
    cout << -1;
}
