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
100
101
#include <bits/stdc++.h>
using namespace std;
#define V vector
#define Q queue
#define PQ priority_queue
#define ST stack
#define UMAP unordered_map
typedef long long LL;
typedef pair<int, int> PII;
typedef V<int> VI;
typedef V<V<int>> VVI;

constexpr int INF = 1'000'000'007;

void bfs(int v, VI& dist, VVI& g) {
    queue<int> q;
    q.push(v);
    dist[v] = 0;
    while (!q.empty()) {
        v = q.front();
        q.pop();
        for (const auto& u : g[v]) {
            if (dist[u] != -1)
                continue;
            dist[u] = dist[v]+1;
            q.push(u);
        }
    }
}

void bfs_conn(int v, VI& dist, VVI& g, int a, int b) {
    queue<int> q;
    if (v == a || v == b) {
        q.push(a);
        q.push(b);
        dist[a] = 0;
        dist[b] = 0;
    } else {
        q.push(v);
        dist[v] = 0;
    }
    while (!q.empty()) {
        v = q.front();
        q.pop();
        for (const auto& u : g[v]) {
            if (dist[u] != -1)
                continue;
            if (u == a || u == b) {
                dist[a] = dist[v]+1;
                dist[b] = dist[v]+1;
                q.push(a);
                q.push(b);
            } else {
                dist[u] = dist[v]+1;
                q.push(u);
            }
        }
    }
}

void solve() {
    int n;
    cin >> n;
    string s;
    VVI g(n);
    for (int i = 0; i < n; ++i) {
        cin >> s;
        for (int j = 0; j < n; ++j)
            if (s[j] == '1')
                g[i].push_back(j);
    }

    int res = INF;
    for (int a = 0; a < n; ++a) {
        for (int b = 0; b < n; ++b) {
            int vol = 0;
            for (int i = 0; i < n; ++i) {
                VI dist_conn(n, -1);
                bfs_conn(i, dist_conn, g, a, b);
                for (int j = 0; j < n; ++j) {
                    vol = max(vol, dist_conn[j]);
                }
            }
            res = min(res, vol);
        }
    }
    cout << res << '\n';
}

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

    int T;
    cin >> T;
    while (T--)
        solve();

    return 0;
}