#include <bits/stdc++.h>
using namespace std;
long long n, m, las, ans;
bitset<512> bz[2][66][512];
struct node {
  long long w;
  bool ty;
  node() {
    w = -3e18;
    ty = 0;
  }
} dp[505];
int main() {
  scanf("%lld%lld", &n, &m);
  long long a, b, c;
  for (int i = 1; i <= m; i++) {
    scanf("%lld%lld%lld", &a, &b, &c);
    bz[c][0][a][b] = 1;
  }
  for (int i = 1; i <= 61; i++)
    for (int u = 1; u <= n; u++)
      for (int v = 1; v <= n; v++) {
        if (bz[0][i - 1][u][v] != 0) bz[0][i][u] |= bz[1][i - 1][v];
        if (bz[1][i - 1][u][v] != 0) bz[1][i][u] |= bz[0][i - 1][v];
      }
  dp[1].w = 0;
  dp[1].ty = 0;
  for (int i = 61; i >= 0; i--)
    for (int u = 1; u <= n; u++)
      for (int v = 1; v <= n; v++)
        if (bz[dp[u].ty][i][u][v] && (dp[v].w < (dp[u].w + (1ll << i)))) {
          dp[v].w = dp[u].w + (1ll << i);
          dp[v].ty = !dp[u].ty;
          ans = max(ans, dp[v].w);
        }
  printf("%lld", (ans > 1e18) ? -1 : ans);
  return 0;
}
