local n, m = io.read("*n", "*n")
local ps, qs, cs = {}, {}, {}
local companies = {}
local stations = {}
for i = 1, n do
  stations[i] = {}
end
for i = 1, m do
  local p, q, c = io.read("*n", "*n", "*n")
  if not companies[c] then companies[c] = {} end
  if stations[p][c] and stations[q][c] then
    if stations[p][c] ~= stations[q][c] then
      local ci_p, ci_q = stations[p][c], stations[q][c]
      if #companies[c][ci_p] < #companies[c][ci_q] then
        for j = 1, #companies[c][ci_p] do
          local st = companies[c][ci_p][j]
          stations[st][c] = ci_q
          table.insert(companies[c][ci_q], st)
        end
        companies[c][ci_p] = {}
      else
        for j = 1, #companies[c][ci_q] do
          local st = companies[c][ci_q][j]
          stations[st][c] = ci_p
          table.insert(companies[c][ci_p], st)
        end
        companies[c][ci_q] = {}
      end
    end
  elseif not stations[p][c] and not stations[q][c] then
    table.insert(companies[c], {p, q})
    stations[p][c] = #companies[c]
    stations[q][c] = #companies[c]
  elseif stations[p][c] then
    local idx = stations[p][c]
    stations[q][c] = idx
    table.insert(companies[c][idx], q)
  else
    local idx = stations[q][c]
    stations[p][c] = idx
    table.insert(companies[c][idx], p)
  end
end
local len = {}
for company, groups in pairs(companies) do
  len[company] = {}
  for i = 1, #groups do
    len[company][i] = -1
  end
end

local tasks = {}
for company, group in pairs(stations[1]) do
  len[company][group] = 1
  table.insert(tasks, {company, group})
end
while 0 < #tasks do
  local src_company, src_group = tasks[#tasks][1], tasks[#tasks][2]
  local srclen = len[src_company][src_group]
  table.remove(tasks)
  for i = 1, #companies[src_company][src_group] do
    local station = companies[src_company][src_group][i]
    for dst_company, dst_group in pairs(stations[station]) do
      if src_company ~= dst_company then
        local dstlen = len[dst_company][dst_group]
        if dstlen == -1 or srclen + 1 < dstlen then
          len[dst_company][dst_group] = srclen + 1
          table.insert(tasks, {dst_company, dst_group})
        end
      end
    end
  end
end
local ret = -1
local mmi = math.min
for company, group in pairs(stations[n]) do
  local dstlen = len[company][group]
  if 0 < dstlen then
    if ret == -1 then
      ret = dstlen
    else
      ret = mmi(ret, dstlen)
    end
  end
end
print(ret)
