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
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

int najdluzsza_sciezka(int n, vector<vector<pair<int, int>>> const &g) {
	vector<bool> vis(n, 0);
	int ans = 0;
	pair<int, int> oddalony = make_pair(0, 1);
	deque<pair<int, int>> Q;
	Q.push_back({0, 0});
	while(Q.size()) {
		auto[v, d] = Q.front(); Q.pop_front();
		if(vis[v]) continue;
		vis[v] = 1;
		oddalony = max(oddalony, make_pair(d, v));
		for(auto[u, w] : g[v]) {
			if(w==1) Q.push_back({u, d+1});
			else Q.push_front({u, d});
		}
	}
	Q.push_front({oddalony.second, 0});
	vis.assign(n, 0);
	while(Q.size()) {
		auto[v, d] = Q.front(); Q.pop_front();
		if(vis[v]) continue;
		vis[v] = 1;
		ans = max(ans, d);
		for(auto[u, w] : g[v]) {
			if(w==1) Q.push_back({u, d+1});
			else Q.push_front({u, d});
		}
	}
	return ans;
}

void solve() {
	int n;
	cin >> n;
	vector<vector<pair<int, int>>> g(n, vector<pair<int, int>>(n));
	for(int i=0; i<n; ++i) {
		string s;
		cin >> s;
		for(int j=0; j<n; ++j) {
			if(s[j]=='1') {
				g[i].push_back({j, 1});
				g[j].push_back({i, 1});
			}
		}
	}
	int ans = INT_MAX;
	for(int i=0; i<n; ++i) {
		for(int j=i+1; j<n; ++j) {
			vector<vector<pair<int, int>>> ng = g;
			ng[i].push_back({j, 0});
			ng[j].push_back({i, 0});
			ans = min(ans, najdluzsza_sciezka(n, ng));
		}
	}
	cout << ans << "\n";
}

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