#include using namespace std; #define rep(i, x) for(int i = 0; i < (x); i++) constexpr int inf = 1 << 30; using T = tuple; int bit; int main() { int n, m; cin >> n >> m; vector edges; vector>> g(n); auto is_palindrome = [](const string &s) { rep(i, s.size()) { if(s[i] != s[s.size() - 1 - i]) return false; } return true; }; auto bfs = [&](int s) { vector dist(n, inf); dist[s] = 0; queue que; que.push(s); while(que.size()) { int now = que.front(); que.pop(); for(auto [to, ignored] : g[now]) { if(dist[to] <= dist[now] + 1) continue; dist[to] = dist[now] + 1; que.push(to); } } return dist; }; auto out = [](vector &res) { reverse(res.begin(), res.end()); cout << res.size() << endl; for(auto &v : res) cout << v + 1 << endl; exit(0); }; rep(i, m) { int a, b; char c; cin >> a >> b >> c; --a, --b; g[a].emplace_back(b, i); g[b].emplace_back(a, i); edges.push_back({a, b, c - 'a'}); bit |= 1 << (c - 'a'); } if(__builtin_popcount(bit) == 1) { puts("-1"); return 0; } auto dist = bfs(0); vector res; string tmp = ""; { int now = n - 1; while(now) { for(auto [to, id] : g[now]) { if(dist[to] + 1 == dist[now]) { now = to; tmp.push_back(get<2>(edges[id])); res.push_back(id); break; } } } } if(not is_palindrome(tmp)) { out(res); } if(count(tmp.begin(), tmp.end(), tmp.front()) != tmp.size()) { rep(i, 2) res.push_back(res.back()); out(res); } rep(i, m) { auto [u, v, e] = edges[i]; if(e == tmp.front()) continue; res.clear(); tmp.clear(); if(dist[u] > dist[v]) swap(u, v); //0恋悉u u->v v->u u恋悉n auto d2 = bfs(u); { int now = n - 1; while(now != u) { for(auto [to, id] : g[now]) { if(d2[to] + 1 == d2[now]) { now = to; tmp.push_back(get<2>(edges[id])); res.push_back(id); break; } } } } rep(j, 2) { tmp.push_back((char)('a' + e)); res.push_back(i); } { int now = u; while(now) { for(auto [to, id] : g[now]) { if(dist[to] + 1 == dist[now]) { now = to; tmp.push_back(get<2>(edges[id])); res.push_back(id); break; } } } } break; } if(is_palindrome(tmp)) { rep(i, 2) res.push_back(res.back()); } out(res); }