package main

import (
	"bufio"
	"container/heap"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
)

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n, m int
var P, Q, C []int

type Node struct {
	// 駅ID, （直前の）会社ID
	stId, compId int
}

// 存在するノードの一覧（逆引き辞書を作るため一時的なもの）
var nodeList []Node

// ノードから一意なidxを取得するための逆引き辞書
var nodeIdxMap map[Node]int

type Edge struct {
	// ノードのハッシュID, コスト
	hashId, cost int
}

// var dp [100000 + 5]map[int]int
// var flags [100000 + 5]map[int]bool
var edges map[int][]Edge
var dp map[int]int
var flags map[int]bool

func main() {
	n, m = ReadInt(), ReadInt()
	P, Q, C = make([]int, m), make([]int, m), make([]int, m)
	for i := 0; i < m; i++ {
		p, q, c := ReadInt()-1, ReadInt()-1, ReadInt()
		P[i], Q[i], C[i] = p, q, c
	}

	nodeList = make([]Node, 0, 300000)
	for i := 0; i < n; i++ {
		// 改札の外はすべての駅に存在する
		nodeList = append(nodeList, Node{stId: i, compId: -1})
	}
	for i := 0; i < m; i++ {
		p, q, c := P[i], Q[i], C[i]
		nodeList = append(nodeList, Node{stId: q, compId: c})
		nodeList = append(nodeList, Node{stId: p, compId: c})
	}
	// 逆引き辞書の作成
	nodeIdxMap = make(map[Node]int)
	for _, node := range nodeList {
		idx := hash(node.stId, node.compId)
		nodeIdxMap[node] = idx
	}

	// 存在する頂点にエッジを張る
	// 1. 改札の出入り
	edges = make(map[int][]Edge)
	for _, node := range nodeList {
		if node.compId == -1 {
			continue
		}
		outHash := nodeIdxMap[Node{stId: node.stId, compId: -1}]
		inHash := nodeIdxMap[Node{stId: node.stId, compId: node.compId}]
		if _, ok := edges[outHash]; !ok {
			edges[outHash] = []Edge{}
		}
		if _, ok := edges[inHash]; !ok {
			edges[inHash] = []Edge{}
		}
		// 外->内はコスト1, 内->外はコスト0
		edges[outHash] = append(edges[outHash], Edge{hashId: inHash, cost: 1})
		edges[inHash] = append(edges[inHash], Edge{hashId: outHash, cost: 0})
	}
	// 2. 路線の移動（同じ会社の路線を継続する）
	for i := 0; i < m; i++ {
		p, q, c := P[i], Q[i], C[i]
		fromHash := nodeIdxMap[Node{stId: p, compId: c}]
		toHash := nodeIdxMap[Node{stId: q, compId: c}]
		if _, ok := edges[fromHash]; !ok {
			edges[fromHash] = []Edge{}
		}
		if _, ok := edges[toHash]; !ok {
			edges[toHash] = []Edge{}
		}
		edges[fromHash] = append(edges[fromHash], Edge{hashId: toHash, cost: 0})
		edges[toHash] = append(edges[toHash], Edge{hashId: fromHash, cost: 0})
	}

	dp = make(map[int]int)
	flags = make(map[int]bool)
	for _, node := range nodeList {
		dp[nodeIdxMap[node]] = INF_BIT60
		flags[nodeIdxMap[node]] = false
	}
	dp[hash(0, -1)] = 0

	temp := make(StationPQ, 0, 100000+1)
	pq := &temp
	heap.Init(pq)
	heap.Push(pq, &Station{priority: dp[hash(0, -1)], hashId: hash(0, -1)})
	for pq.Len() > 0 {
		curSt := heap.Pop(pq).(*Station)
		hashId := curSt.hashId
		for _, e := range edges[hashId] {
			toHashId := e.hashId
			if dp[toHashId] > dp[hashId]+e.cost {
				dp[toHashId] = dp[hashId] + e.cost
				heap.Push(pq, &Station{priority: dp[toHashId], hashId: toHashId})
			}
		}
	}

	if dp[hash(n-1, -1)] != INF_BIT60 {
		fmt.Println(dp[hash(n-1, -1)])
	} else {
		fmt.Println(-1)
	}
}

func hash(stId, compId int) int {
	id := compId*PowInt(10, 6) + stId
	return id
}

type Station struct {
	priority int
	hashId   int
}
type StationPQ []*Station

func (pq StationPQ) Len() int           { return len(pq) }
func (pq StationPQ) Less(i, j int) bool { return pq[i].priority < pq[j].priority } // <: ASC, >: DESC
func (pq StationPQ) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}
func (pq *StationPQ) Push(x interface{}) {
	item := x.(*Station)
	*pq = append(*pq, item)
}
func (pq *StationPQ) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

// how to use
// temp := make(StationPQ, 0, 100000+1)
// pq := &temp
// heap.Init(pq)
// heap.Push(pq, &Station{priority: intValue})
// popped := heap.Pop(pq).(*Station)

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

/*******************************************************************/

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// CeilInt returns the minimum integer larger than or equal to float(a/b).
func CeilInt(a, b int) int {
	res := a / b
	if a%b > 0 {
		res++
	}
	return res
}

// FloorInt returns the maximum integer smaller than or equal to float(a/b)
func FloorInt(a, b int) int {
	res := a / b
	return res
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

// Strtoi is a wrapper of `strconv.Atoi()`.
// If `strconv.Atoi()` returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}


Measured memory_bytes: 208000