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
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned int uint;

int t, n, best;
char c;
vector<pair<int, bool>> graf[400];
bitset<400> odw;
deque<pair<int, int>> dq;

int ecc(int w)
{
    int wynik = 0;
    odw.reset();
    dq.push_back({ w, 0 });
    while (!dq.empty())
    {
        auto p = dq.front();
        dq.pop_front();
        if (odw[p.first]) continue;
        odw[p.first] = true;
        wynik = max(wynik, p.second);
        for (auto sp : graf[p.first])
        {
            if (odw[sp.first]) continue;
            if (sp.second) dq.push_back({ sp.first, p.second+1 });
            else dq.push_front({ sp.first, p.second });
        }
    }
    //cout << wynik << '\n';
    return wynik;
}

int dia()
{
    int wynik = 0;
    for (int w = 0; w < n; w++)
        wynik = max(wynik, ecc(w));
    return wynik;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cout.tie(nullptr);
    cin.tie(nullptr);

    cin >> t;
    for (int _ = 0; _ < t; _++)
    {
        cin >> n;

        best = 1000000;
        for (int i = 0; i < n; i++)
            graf[i].clear();

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cin >> c;
                if (c == '1') graf[i].push_back({ j, 1 });
            }
        }

        for (int i = 0; i < n; i++)
        {
            for (int j = i+1; j < n; j++)
            {
                graf[i].push_back({ j, 0 });
                graf[j].push_back({ i, 0 });
                best = min(best, dia());
                //cout << i << ' ' << j << ' ' << dia() << '\n';
                graf[i].pop_back();
                graf[j].pop_back();
            }
        }

        cout << best << '\n';
    }

    return 0;
}