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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// #pragma GCC optimize("O3")
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,bmi,bmi2,lzcnt,abm,mmx,avx,avx2,tune=native")

#include <bits/stdc++.h>

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;

// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

#define rep(i, j) for (int i = 0; i < ((int)(j)); i++)
#define pb push_back
#define pf push_front
#define st first
#define nd second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define get_unique(x) x.erase(unique(all(x)), x.end());

const int N = 405;
int n;
bitset<N> cur, nxt, vis;
vector<bitset<N>> g2;

int calc_dst_from(int x) {
  cur.reset();
  nxt.reset();
  vis.reset();
  int dst = 0;
  cur[x] = 1;
  vis[x] = 1;
  while (cur.count()) {
    int it = cur._Find_first();
    while (it != N) {
      vis[it] = true;
      nxt |= g2[it];
      it = cur._Find_next(it);
    }
    nxt &= ~vis;
    cur = nxt;
    nxt.reset();
    dst++;
  }

  return dst - 1;
}

int calc_diam(int ignore = -1) {
  int ans = 0;
  rep(i, n) {
    if (i == ignore)
      continue;
    ans = max(ans, calc_dst_from(i));
  }
  return ans;
}

void TEST([[maybe_unused]] int testcase_i) {
  cin >> n;

  vector<bitset<N>> g(n + 1);
  rep(i, n) {
    string s;
    cin >> s;
    rep(j, n) {
      g[i][j] = s[j] - '0';
    }
  }

  g2 = g;
  int ans = calc_diam();

  for (int l = 0; l < n; l++) {
    for (int r = l + 1; r < n; r++) {
      g2 = g;
      rep(i, n) {
        if (g2[i][r])
          g2[i][l] = true;
        g2[i][r] = false;
      }

      g2[l] |= g2[r];
      g2[l][l] = false;
      g2[l][r] = false;

      ans = min(ans, calc_diam(r));
    }
  }

  cout << ans << "\n";
}

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

  // cout << setprecision(20) << fixed;

  // srand(time(NULL));

  // freopen("sorting.in", "r", stdin);
  // freopen("sorting.out", "w", stdout);

  int t = 1;
  cin >> t;
  rep(i, t) {
    TEST(i);
  }

  return 0;
}