#include <bits/stdc++.h>
#pragma GCC optimize("-O3")
using namespace std;
const long long mod = 998244353;
const int N = 505;
bitset<N> p[61][N], pcol[61][N], b[61][N], bcol[61][N];
int n, m, u, v, typ;
int cnt = 0;
long long cr;
void solve() {
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    cin >> u >> v >> typ;
    u--, v--;
    if (typ == 0) {
      p[0][u].set(v);
      pcol[0][v].set(u);
    } else {
      b[0][u].set(v);
      bcol[0][v].set(u);
    }
  }
  for (int k = 1; k <= 60; k++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        if ((p[k - 1][i] & bcol[k - 1][j]).any()) {
          p[k][i].set(j);
          pcol[k][j].set(i);
        }
        if ((b[k - 1][i] & pcol[k - 1][j]).any()) {
          b[k][i].set(j);
          bcol[k][j].set(i);
        }
      }
    }
  }
  vector<int> reach{0};
  cr = 0;
  for (int k = 60; k >= 0; k--) {
    bitset<N> tmp(0);
    for (int x : reach) {
      if (cnt) {
        tmp |= b[k][x];
      } else {
        tmp |= p[k][x];
      }
    }
    if (!tmp.any()) continue;
    cr += 1ll << k;
    if (k == 60) break;
    cnt ^= 1;
    vector<int> tmpre;
    for (int i = 0; i < n; i++) {
      if (tmp.test(i)) {
        tmpre.push_back(i);
      }
    }
    reach.swap(tmpre);
  }
  if (cr > (long long)1e18) cr = -1;
  cout << cr << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t--) {
    solve();
  }
}
