涉及知识点:
solution:
- (做法较多,这里提两种容易理解的做法:)
- (做法1,直接bfs,想象成一个图)
- (将每一个字符串的首位和末位相连,比如bcde,就可以理解成b到e连一条线)
- (那么题目就变成了求a到b最短需要走几条路,直接bfs即可)
- (那显然做法2也出来了,直接求a到所有点的最短路,如果a到b的距离是inf,则输出-1)
BFSstd:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 105;
struct node{
int x,w;
};
vector<int> v[maxn];
int flag[maxn];
map<char,int> mp;
int ans = -1;
void bfs(int x){
queue<node> q;
q.push(node{x,0});
flag[1] = 1;
while(!q.empty()){
node now = q.front();
q.pop();
if(now.x == 2){
ans = now.w;
break ;
}
int siz = v[now.x].size();
for(int i=0;i<siz;i++){
if(flag[v[now.x][i]] == 0){
flag[v[now.x][i]] = 1;
q.push(node{v[now.x][i] , now.w + 1});
}
}
}
return ;
}
int main()
{
int n,cnt = 2;
string s;
char a,b;
cin>>a>>b;
mp[a] = 1,mp[b] = 2;
cin>>n;
for(int i=1;i<=n;i++){
cin>>s;
if(mp[s[0]] == 0){
mp[s[0]] = ++cnt;
}
if(mp[s[3]] == 0){
mp[s[3]] = ++cnt;
}
int x = mp[s[0]] , y = mp[s[3]];
v[x].push_back(y);
}
bfs(1);
cout<<ans<<endl;
return 0;
}
最短路std:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 105;
const int inf = 1e9;
struct node{
int to;
int w;
friend bool operator <(node p1,node p2){
return p1.w > p2.w;
}
};
vector<node> v[maxn];
priority_queue<node> q;
int dis[maxn] , cnt = 2 ,n;
void spfa(int s){
fill(dis+1,dis+1+cnt,inf);
dis[s] = 0;
while(!q.empty()) q.pop();
q.push(node{s,0});
while(!q.empty())
{
node x = q.top();q.pop();
int k = x.to;
int w = x.w;
if(w > dis[k])
continue;
int siz = v[k].size();
for(int i=0;i<siz;i++){
if(dis[v[k][i].to] > w + v[k][i].w){
dis[v[k][i].to] = w + v[k][i].w;
q.push(node{v[k][i].to,dis[v[k][i].to]});
}
}
}
}
map<char,int> mp;
int main()
{
string s;
char a,b;
cin>>a>>b;
mp[a] = 1,mp[b] = 2;
cin>>n;
for(int i=1;i<=n;i++){
cin>>s;
if(mp[s[0]] == 0){
mp[s[0]] = ++cnt;
}
if(mp[s[3]] == 0){
mp[s[3]] = ++cnt;
}
int x = mp[s[0]] , y = mp[s[3]];
v[x].push_back(node{y,1});
}
spfa(1);
int ans = dis[2];
if(dis[2] == inf)
ans = -1;
cout<<ans<<endl;
return 0;
}