#include <bits/stdc++.h>

using namespace std;

vector<pair<int, int>> edges[26];
vector<pair<int, int>> states[1024][1024];
int d[1024][1024];

int main()
{
  int N, M;
  
  scanf("%d %d", &N, &M);
  
  queue<pair<int, int>> q;
  for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= N; j++) {
      d[i][j] = 1'000'000'000;
    }
    d[i][i] = 0; q.emplace(i, i);
  }
  
  for (int i = 0; i < M; i++) {
    int u, v; char c[2];
    scanf("%d %d %s", &u, &v, c);
    if (u > v) swap(u, v);
    edges[c[0] - 'a'].emplace_back(u, v);
    if (u != v) d[u][v] = d[v][u] = 1;
    q.emplace(u, v);
  }
  
  for (int a = 0; a < 26; a++) {
    int sz = edges[a].size();
    for (int i = 0; i < sz; i++) {
      for (int j = i + 1; j < sz; j++) {
        auto [u, v] = edges[a][i];
        auto [w, x] = edges[a][j];
        states[u][w].emplace_back(v, x); states[w][u].emplace_back(v, x);
        states[u][x].emplace_back(v, w); states[x][u].emplace_back(v, w);
        states[v][w].emplace_back(u, x); states[w][v].emplace_back(u, x);
        states[v][x].emplace_back(u, w); states[x][v].emplace_back(u, w);
      }
    }
  }
  
  while (q.size()) {
    auto [u, v] = q.front(); q.pop();
    if (u > v) swap(u, v);
    if (u == 1 && v == N) {
      printf("%d\n", d[u][v]); return 0;
    }
    for (auto [u2, v2] : states[u][v]) {
      if (d[u2][v2] == 1'000'000'000) {
        d[u2][v2] = d[v2][u2] = d[u][v] + 2;
        q.emplace(u2, v2);
      }
    }
  }
  
  printf("-1\n");
  
  return 0;
}
#include<bits/stdc++.h>
using namespace std;
#define ll long long 
int main()
{
    int n,m;
  	int vdnmcjdkmkh; 
    cin>>n>>m;
    vector<pair<int,int>>a(m);
    for(int i=0;i<m;i++)
    {
        cin>>a[i].first>>a[i].second;
    }
    int k;
    cin>>k;
    vector<pair<int,int>>b(k);
    for(int j=0;j<k;j++)
    {
        cin>>b[j].first>>b[j].second;
    }
    ll l=0;
    ll tot=1<<k;
    for(ll mask=0;mask<tot;mask++)
    {
        vector<int>v(n+1);
        ll ans=0;
        for(int i=0;i<k;i++)
        {
            if(mask & (1<<i))
                v[b[i].second]=1;
            else
                v[b[i].first]=1;
        }
        for(int i=0;i<m;i++)
        {
            if(v[a[i].first] && v[a[i].second])
                ans++;
        }
        l=max(l,ans);
    }
    cout<<l<<endl;
    return 0;
}