#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
const long long INF = 1e18;
const long long mod = 1000000007;
bitset<505> dp[63][2][505];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int u, v, flag;
    scanf("%d%d%d", &u, &v, &flag);
    dp[0][flag][u][v] = 1;
  }
  for (int s = 1; s <= 60; s++) {
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= n; j++) {
        if (dp[s - 1][0][i][j]) dp[s][0][i] |= dp[s - 1][1][j];
        if (dp[s - 1][1][i][j]) dp[s][1][i] |= dp[s - 1][0][j];
      }
    }
  }
  long long ans = 0;
  int op = 0;
  bitset<505> g, tmp;
  g[1] = 1;
  for (int s = 60; s >= 0; s--) {
    tmp &= 0;
    for (int i = 1; i <= n; i++) {
      if (g[i]) {
        tmp |= dp[s][op][i];
      }
    }
    if (tmp.count() > 0) {
      g = tmp;
      ans += (1ll << s);
      op ^= 1;
    }
  }
  if (ans > INF)
    printf("-1\n");
  else
    printf("%lld\n", ans);
  return 0;
}
