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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include <bits/stdc++.h>
using namespace std;

#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define RFOR(i, a, b) for(int i = (a) - 1; i >= (b); i--)
#define SZ(a) int(a.size())
#define ALL(a) a.begin(), a.end()
#define PB push_back
#define MP make_pair
#define F first
#define S second

typedef long long LL;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
typedef double db;

const int N = 474;

template<typename T>
void updMin(T& a, T b)
{
	a = min(a, b);
}

template<typename T>
void updMax(T& a, T b)
{
	a = max(a, b);
}

int n;
int d[N][N];
int b[N];
PII q[N * N];

bool check(int m, int u)
{
	FOR(i, 0, n)
	{
		b[i] = N;
	}
	int szQ = 0;
	FOR(i, 0, n)
	{
		FOR(j, i + 1, n)
		{
			if (d[i][j] <= m)
				continue;
			if (d[u][i] < d[u][j])
				updMin(b[j], m - d[u][i]);
			else if (d[u][j] < d[u][i])
				updMin(b[i], m - d[u][j]);
			else if (d[i][j] > m + 1)
				return false;
			else
			{
				q[szQ++] = {i, j};
			}
		}
	}
	FOR(v, 0, n)
	{
		bool ok = true;
		FOR(i, 0, n)
		{
			ok &= d[v][i] <= b[i];
		}
		if (!ok)
			continue;
		FOR(k, 0, szQ)
		{
			auto [i, j] = q[k];
			ok &= min(d[v][i], d[v][j]) + d[u][i] <= m;
			if (!ok)
				break;
		}
		if (ok)
			return true;
	}
	return false;
}

bool check(int m)
{
	FOR(u, 0, n)
	{
		if (check(m, u))
		{
			return true;
		}
	}
	return false;
}

void solve()
{
	cin >> n;
	FOR(i, 0, n)
	{
		string s;
		cin >> s;
		FOR(j, 0, n)
		{
			if (i == j)
				d[i][j] = 0;
			else if (s[j] == '0')
				d[i][j] = N;
			else
				d[i][j] = 1;
		}
	}
	FOR(k, 0, n)
	{
		FOR(i, 0, n)
		{
			FOR(j, 0, n)
			{
				updMin(d[i][j], d[i][k] + d[k][j]);
			}
		}
	}
	int l = 0, r = 0;
	FOR(i, 0, n)
	{
		FOR(j, 0, n)
		{
			updMax(r, d[i][j]);
		}
	}
	while (r - l > 1)
	{
		int m = (l + r) / 2;
		if (check(m))
			r = m;
		else
			l = m;
	}
	cout << r << "\n";
}

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