原题链接
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1010, M = 4010;
int h1[N], h2[N], e[M], ne[M], w[M], n, m, idx;
int f[N][N];
PII q[N * N];
int ans = 1e9;
void add(int h[], int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
int bfs(int fr, int to) {
int hh = 0, tt = -1;
f[fr][to] = 0;
q[++ tt] = {fr, to};
while (hh <= tt) {
auto t = q[hh ++];
int t1 = t.x, t2 = t.y;
for (int i1 = h1[t1]; i1 != -1; i1 = ne[i1])
for (int i2 = h2[t2]; i2 != -1; i2 = ne[i2]) {
if (w[i1] != w[i2]) continue;
int j1 = e[i1], j2 = e[i2];
if (f[j1][j2] != -1) continue;
if (t1 == j2 && t2 == j1)
ans = min(ans, f[t1][t2] + 1);
else if (j1 == j2)
ans = min(ans, f[t1][t2] + 2);
f[j1][j2] = f[t1][t2] + 2;
q[++ tt] = {j1, j2};
}
}
if (ans == 1e9) return -1;
return ans;
}
int main() {
memset(h1, -1, sizeof h1);
memset(h2, -1, sizeof h2);
memset(f, -1, sizeof f);
cin >> n >> m;
for (int i = 0; i < m; i ++) {
int a, b, c;
char ch[2];
cin >> a >> b >> ch;
c = ch[0] - '\0';
add(h1, a, b, c), add(h1, b, a, c);
add(h2, a, b, c), add(h2, b, a, c);
}
cout << bfs(1, n);
return 0;
}