#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
vector<int> G[N];
int pos = -1;
vector<int> vec;
bool visited[N];
void dfs(int u, int step, int fa, int uu) {
if (step == 3) {
if (u == uu) {
pos = u;
}
return;
}
if (visited[u]) {
return;
}
visited[u] = true;
for (auto v : G[u]) {
if (v != fa) {
dfs(v, step + 1, u, uu);
}
}
}
void dfs2(int u, int step) {
if (step > 3) {
return;
}
if (u == pos && step) {
vec.pop_back();
for (auto x : vec) {
cout << x << " ";
}
cout << "\n";
exit(0);
}
for (auto v : G[u]) {
vec.push_back(v);
dfs2(v, step + 1);
vec.pop_back();
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
for (int j = 1; j <= n; j++) {
int op = s[j - 1] - '0';
if (op) {
G[i].push_back(j);
}
}
}
for (int i = 1; i <= n; i++) {
memset(visited, false, sizeof(visited));
dfs(i, 0, -1, i);
if (pos != -1) {
break;
}
}
if (pos != -1) {
memset(visited, false, sizeof(visited));
vec.push_back(pos);
dfs2(pos, 0);
} else {
cout << pos << " ";
}
return 0;
}
这不是 O(n2) 的复杂度吗?
为啥超时了呢?