import sys from collections import deque sys.setrecursionlimit(10**7) def I(): return int(sys.stdin.readline().rstrip()) def MI(): return map(int,sys.stdin.readline().rstrip().split()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def LI2(): return list(map(int,sys.stdin.readline().rstrip())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) def LS2(): return list(sys.stdin.readline().rstrip()) N,M = MI() Graph = [[] for _ in range(N+1)] edges = [] char = set() for i in range(1,M+1): A,B,C = S().split() A = int(A) B = int(B) Graph[A].append((B,C,i)) Graph[B].append((A,C,i)) edges.append((A,B,C)) char.add(C) if len(char) == 1: print(-1) exit() s,a,idx = Graph[1][0] for i in range(M): A,B,C = edges[i] if a != C: goal = A e = i+1 goal2 = B inf = 10**18 dist = [inf]*(N+1) dist[N] = (0,-1,-1) deq = deque([N]) while deq: u = deq.pop() if u == goal: break for v,_,i in Graph[u]: if dist[v] == inf: dist[v] = (dist[u][0]+1,i,u) deq.appendleft(v) ANS1 = [e] ss = goal while ss != N: d,i,u = dist[ss] ANS1.append(i) ss = u ANS0 = [idx]*len(ANS1) if len(ANS0) % 2 == 1: cur = s else: cur = 1 dist = [inf]*(N+1) dist[B] = (0,-1,-1) deq = deque([B]) while deq: u = deq.pop() if u == cur: break for v,_,i in Graph[u]: if dist[v] == inf: dist[v] = (dist[u][0]+1,i,u) deq.appendleft(v) s = cur while s != B: d,i,u = dist[s] ANS0.append(i) s = u ANS = ANS0+ANS1 print(len(ANS)) print(*ANS,sep='\n')