解法:
每次加入所有邻接点
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int arr[100][100];
string vertex;
void bfs(vector<int>& a,int u) {
queue<int> q;
a[u] = 1;
q.push(u);
while (!q.empty()) {
int v = q.front();
for (int i = 0; i < a.size(); i++) {
if (arr[v][i] && !a[i]) {
q.push(i);
a[i] = 1;
}
}
cout << vertex[v];
q.pop();
}
}
int main() {
int n;
cin >> n;
vector<int> vis(n, 0);
cin >> vertex;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> arr[i][j];
char x;
cin >> x;
int pos;
for (pos=0; pos < vertex.size(); pos++) {
if (x == vertex[pos])
break;
}
bfs(vis, pos);
return 0;
}