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
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n; cin >> n;
    vector<string> a(n);
    for (string &s: a) cin >> s;

    vector dist(n, vector<int>(n, 1e9));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i][j] == '1') dist[i][j] = 1;
            if (i == j) dist[i][j] = 0;
        }
    }

    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }


    int res = n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < i; j++) {
            int diam = 0;
            for (int a = 0; a < n; a++) {
                for (int b = 0; b < a; b++) {
                    int cur = dist[a][b];
                    cur = min(cur, dist[a][i] + dist[j][b]);
                    cur = min(cur, dist[a][j] + dist[i][b]);
                    diam = max(diam, cur);
                    if (diam >= res) break;
                }
                if (diam >= res) break;
            }
            res = min(res, diam);
        }
    }
    cout << res << '\n';
}

int main() {
    int tc; cin >> tc;
    while (tc--) solve();
}