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
90
91
92
93
94
95
96
97
98
99
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <numeric>
#include <stack>
using namespace std;
using ll = long long int;
#define debug(x) cout << #x << " = " << x << endl;
int bfs(vector<set<int>>& v, int mniejsza, int wieksza, int start, int n)
{
    int odp = 0;
    vector<int>odl(n, 0);
    if (start == wieksza)
        start = mniejsza;//zacznij od mniejszej ignoruj wieksza
    odl[start] = 0;
    queue<int>q;
    q.push(start);
    while (!q.empty())
    {
        int obecny = q.front();
        q.pop();
        for (int sasiad : v[obecny])
        {
            if (sasiad == wieksza)//traktuj jako mniejsza
            {
                sasiad = mniejsza;
            }
            if (odl[sasiad] == 0 && sasiad != start)
            {
                odl[sasiad] = odl[obecny] + 1;
                odp = max(odp, odl[sasiad]);
                q.push(sasiad);
            }
        }
    }
    return odp;
}
void solve()
{
    int n;
    cin >> n;
    vector<set<int>>v(n);
    for (int i = 0; i < n; i++)
    {
        string s;
        cin >> s;
        for (int j = 0; j < n; j++)
        {
            if (s[j] != '0')
                v[i].insert(j);
        }
    }
    int odp = 1e9;
    for (int a = 0; a < n; a++)
    {
        for (int b = a + 1; b < n; b++)
        {
            //dodaj do mniejszego
            vector<int>cododano;
            for (int x : v[b])
            {
                if (x != b && v[a].find(x) == v[a].end())
                {
                    v[a].insert(x);
                    cododano.push_back(x);
                }
            }
            int p = 0;
            for (int start = 0; start < n; start++)
            {
                p = max(p, bfs(v, a, b, start, n));
                //cout << "odp:" << start << " " << p << endl;
            }
            for (int x : cododano)
            {
                v[a].erase(x);
            }
            odp = min(odp, p);
        }
    }
    cout << odp << "\n";
}

int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}