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
#include <bits/stdc++.h>
#define MAX_N 407
#define f first
#define s second
using namespace std;

vector<pair<int, int>> graph[MAX_N];
int od[MAX_N];
int vis[MAX_N];
int newT = 1;

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;

void ClearAllData(){
	for(int i = 0; i < MAX_N; i++){
		graph[i].clear();
		od[i] = 0;
		vis[i] = 0;
	}
	newT = 1;
}

void Astar(int w, int k){
	while(!q.empty()) q.pop();
	q.push({0, w});
	int v, t;
	while(!q.empty()){
		while(vis[q.top().s] == k && !q.empty()) q.pop();
		if(q.empty()) break;
		t = q.top().f;
		v = q.top().s;
		od[v] = t;
		vis[v] = k;
		q.pop();
		for(auto& i : graph[v]){
			if(vis[i.f] == k) continue;
			q.push({t + i.s, i.f});
		}
	}
}

void Test(){
	ClearAllData();
	int n;
	cin >> n;
	string s;
	for(int i = 0; i < n; i++){
		cin >> s;
		for(int j = 0; j < i; j++){
			if(s[j] == '0') continue;
			graph[j+1].push_back({i+1, 1});
			graph[i+1].push_back({j+1, 1});
		}
	}
	pair<int, int> p;
	int minResult = n;
	for(int i = 1; i <= n; i++){
		for(int j = i+1; j <= n; j++){
			graph[i].push_back({j, 0});
			graph[j].push_back({i, 0});
			Astar(1, newT++);
			p = {0, 0};
			for(int k = 1; k <= n; k++){
				if(p.s < od[k]){
					p.f = k;
					p.s = od[k];
				}
			}
			Astar(p.f, newT++);
			for(int k = 1; k <= n; k++){
				if(p.s < od[k]){
					p.f = k;
					p.s = od[k];
				}
			}
			minResult = min(minResult, p.s);
			for(int k = 0; k < graph[i].size(); k++){
				if(graph[i][k].s == 0){
					graph[i].erase(graph[i].begin() + k, graph[i].begin() + k + 1);
					break;
				}
			}
			for(int k = 0; k < graph[j].size(); k++){
				if(graph[j][k].s == 0){
					graph[j].erase(graph[j].begin() + k, graph[j].begin() + k + 1);
					break;
				}
			}
		}
	}
	cout << minResult << '\n';
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int t;
	cin >> t;
	for(int i = 0; i < t; i++){
		Test();
	}
	return 0;
}