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
#include <iostream>
#include <vector>

using namespace std;

const int inf = 1e9;

void solve(){
    int n; cin>>n;
    int tab[n+7][n+7];
    int dist[n+7][n+7];
    for(int i=1; n>=i; i++){
        string s; cin>>s;
        for(int j=1; n>=j; j++){
            //cin>>tab[i][j];
            if(s[j-1] == '1') tab[i][j] = 1;
            else tab[i][j] = inf;

            if(i == j) tab[i][j] = 0;
        }
    }

    // for(int i=1; n>=i; i++){
    //     for(int j=1; n>=j; j++){
    //         cout<<tab[i][j]<<" ";
    //     }cout<<endl;
    // }cout<<endl;

    int res = inf;

    for(int i=1; n>=i; i++){
        for(int j=i+1; n>=j; j++){
            for(int o=1; n>=o; o++){
                for(int p=1; n>=p; p++){
                    dist[o][p] = tab[o][p];
                }
            }
            
            dist[i][j] = 0;
            dist[j][i] = 0;

            for(int k = 1; k <= n; k++){
                for(int x = 1; x <= n; x++){
                    for(int y = 1; y <= n; y++){
                        dist[x][y] = min(dist[x][y], dist[x][k] + dist[k][y]); 
                    }
                }
            }
            int maxi = -1;
            for(int o=1; n>=o; o++){
                for(int p=1; n>=p; p++){
                    maxi = max(maxi,dist[o][p]);
                }
            }
            res = min(maxi,res);
        }
    }
    cout<<res<<endl;
}

signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int T; cin>>T;
    while(T-->0){
        solve();
    }
}