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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int MAXN = 405;

int odl[MAXN][MAXN];

vector<int> graf[MAXN];
int odw[MAXN];

void odlbfs(int start){
    queue<pair<int,int>> q;
    q.push({start, 0});
    while(!q.empty()){
        auto e = q.front();
        q.pop();
        if(odw[e.first] == 1) continue;
        odl[start][e.first] = e.second;
        odw[e.first] = 1;
        for(auto u : graf[e.first]){
            if(odw[u] == 1) continue;
            q.push({u, e.second + 1});
        }
    }
    return;
}

int wyn(int d1, int d2, int n){
    int c = 0;
    for(int a = 1; a <= n; ++a){
        for(int b = a + 1; b <= n; ++b){
            c = max(c, min(odl[a][b], min(odl[d1][a], odl[d2][a]) + min(odl[d1][b], odl[d2][b])));
        }
    }
    return c;
}

void solve(){
    int n;
    cin >> n;
    string s;
    for(int i = 1; i <= n; ++i){
        cin >> s;
        for(int j = i + 1; j <= n; ++j){
            if((s[j-1]-'0') == 1){
                //cout << i << " " << j << " graf\n";
                graf[i].push_back(j);
                graf[j].push_back(i);
            }
        }
    }
    for(int i = 1; i <= n; ++i){
        odlbfs(i);
        for(int j = 1; j <= n; ++j){
            odw[j] = 0;
        }
    }
    int w = 1e9;
    for(int i = 1; i <= n; ++i){
        for(int j = i + 1; j <= n; ++j){
            int v = wyn(i, j, n);
            //cout << i << " " << j << " " << v << "\n";
            w = min(w, v);
        }
    }
    cout << w << "\n";
    for(int i = 1; i <= n; ++i){
        graf[i].clear();
        for(int j = 1; j <= n; ++j){
            odl[i][j] = 0;
            
        }
        odw[i] = 0;
    }
    return;
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}