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
// Mateusz Macik brut O(n^4)
#include <bits/stdc++.h>
using namespace std;

int INT() {
	int c = getchar_unlocked();
	int x = 0;

	while (c <= '9' && c >= '0') {
		x = 10 * x + (c - '0');
		c = getchar_unlocked();
	}

	return x;
}

// pamietac o resetowaniu wszystkich globalnych rzeczy

vector <vector <bool> > e;

void solve() {
	int n = INT();

	e = vector <vector <bool> > (n+1, vector <bool> (n+1, 0));

	for(int x = 1; x <= n; ++x) {
		for(int y = 1; y <= n; ++y) {
			char c = (char) getchar_unlocked();
			e[x][y] = (c == '1');
		}
		getchar_unlocked();
	}

	int ans = n - 1;

	vector <vector <int> > dist(n+1, vector <int> (n+1, n));
	for(int x = 1; x <= n; ++x) dist[x][x] = 0;
	for(int x = 1; x <= n; ++x) for(int y = x + 1; y <= n; ++y) {
		if(e[x][y]) dist[x][y] = dist[y][x] = 1;
	}
	
	for(int z = 1; z <= n; ++z) for(int x = 1; x <= n; ++x) for(int y = 1; y <= n; ++y) {
		dist[x][y] = min(dist[x][y], dist[x][z] + dist[z][y]);
	}

	// wynik bez teleportu (ciut szybciej)
	int cur = 0;
	for(int x = 1; x <= n; ++x) for(int y = x + 1; y <= n; ++y) cur = max(cur, dist[x][y]);
	ans = min(ans, cur);
	
	for(int a = 1; a <= n; ++a) for(int b = a + 1; b <= n; ++b) {
		cur = 0;
		for(int x = 1; x <= n; ++x) for(int y = x + 1; y <= n; ++y) {
			cur = max(cur, min({dist[x][y], dist[x][a] + dist[b][y], dist[x][b] + dist[a][y]}));
		}
		ans = min(ans, cur);
	}

	printf("%d\n", ans);
}

int main() {
	int t = INT();

	for(++t; --t;) solve();

	return 0;
}