#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const long long INF = 1e18;
bitset<N> dp[63][2][N], tmp, g;
long long ans;
int n, m;
int main() {
  cin >> n >> m;
  for (int i = 1, u, v, w; i <= m; i++) {
    cin >> u >> v >> w;
    dp[0][w][u][v] = 1;
  }
  for (int s = 1; s <= 60; s++)
    for (int j = 0; j < 2; j++)
      for (int u = 1; u <= n; u++)
        for (int v = 1; v <= n; v++)
          if (dp[s - 1][j][u][v]) dp[s][j][u] |= dp[s - 1][j ^ 1][v];
  for (int i = 1; i <= n; i++)
    if (dp[60][0][1][i]) return !printf("-1");
  int t = 0;
  tmp[1] = 1;
  for (int i = 59; i >= 0; i--) {
    g = 0;
    for (int j = 1; j <= n; j++)
      if (tmp[j]) g |= dp[i][t][j];
    if (g.count()) {
      tmp = g;
      t ^= 1;
      ans += (1ll << i);
      if (ans > INF) return !printf("-1");
    }
  }
  if (ans > INF) return !printf("-1");
  return !printf("%lld\n", ans);
}
