#include <bits/stdc++.h>
using namespace std;
const int MAXN = 65;
bitset<500 + 10> f[MAXN][2][500 + 10], las, now;
int n, m;
unsigned long long ans;
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int x, y, z;
    scanf("%d%d%d", &x, &y, &z);
    f[0][z][x][y] = 1;
  }
  for (int i = 1; i < MAXN; i++) {
    for (int j = 0; j < 2; j++) {
      for (int x = 1; x <= n; x++) {
        for (int y = 1; y <= n; y++) {
          if (f[i - 1][j][x][y]) f[i][j][x] |= f[i - 1][j ^ 1][y];
        }
      }
    }
  }
  int fx = 0;
  las[1] = 1;
  for (int i = MAXN - 1; i >= 0; i--) {
    now.reset();
    for (int x = 1; x <= n; x++) {
      if (las[x]) now |= f[i][fx][x];
    }
    if (now.any()) {
      swap(las, now);
      fx ^= 1;
      ans += 1ull << i;
      if (ans >= 1e18) {
        printf("-1\n");
        return 0;
      }
    }
  }
  cout << ans << endl;
  return 0;
}
