#include <bits/stdc++.h>
using namespace std;
#define UwU cout.tie(0); cin.tie(0); ios::sync_with_stdio(0);
void solve() {
int n; cin >> n;
vector<string> graph(n);
for (int i = 0; i < n; i++)
cin >> graph[i];
int res = INT_MAX;
queue<int> q;
for (int i = 0; i < n; i++) {
vector<int> dist(n, -1);
q.push(i);
dist[i] = 0;
int maxi = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v = 0; v < n; v++) {
if (graph[u][v] == '1' && dist[v] == -1) {
dist[v] = dist[u] + 1;
maxi = max(maxi, dist[v]);
q.push(v);
}
}
}
res = min(res, maxi);
}
cout << res << '\n';
}
int main() {
UwU;
int q; cin >> q;
while (q-->0) {
solve();
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <bits/stdc++.h> using namespace std; #define UwU cout.tie(0); cin.tie(0); ios::sync_with_stdio(0); void solve() { int n; cin >> n; vector<string> graph(n); for (int i = 0; i < n; i++) cin >> graph[i]; int res = INT_MAX; queue<int> q; for (int i = 0; i < n; i++) { vector<int> dist(n, -1); q.push(i); dist[i] = 0; int maxi = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (int v = 0; v < n; v++) { if (graph[u][v] == '1' && dist[v] == -1) { dist[v] = dist[u] + 1; maxi = max(maxi, dist[v]); q.push(v); } } } res = min(res, maxi); } cout << res << '\n'; } int main() { UwU; int q; cin >> q; while (q-->0) { solve(); } } |
English