题解
2023-08-14 07:51:39
发布于:四川
31阅读
0回复
0点赞
这个题涉及到一点点图了,题目说的是用邻接矩阵,但是我感觉邻接表好用一些。
就是建个图然后 bfs 一下就行了的事情。
代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main(){
int n,x,y;
cin >> n >> x >> y;
vector<vector<int>> a(n+1);//我更喜欢邻接表
for (int i=1;i<=n;++i){
for (int j=1;j<=n;++j){
int t;
cin >> t;
if (t){
a[i].emplace_back(j);
}
}
}
vector<int> st(n+1,-1);
queue<int> q;
q.emplace(x);
st[x]=0;
while (!q.empty()){
int t=q.front();
q.pop();
if (t==y){
cout<<st[t]-1<<endl;
return 0;
}
for (const auto &item : a[t]){
if (st[item]==-1){
q.emplace(item);
st[item]=st[t]+1;
}
}
}
return 0;
}
这里空空如也
有帮助,赞一个