#include #define mp make_pair #define fi first #define se second #define debug(x) cerr << #x << " = " << (x) << endl #define EPS 1e-9 #define PI acos(-1.0) using namespace std; void test() { cerr << endl; } template void test(T x, Args... args) { cerr << x << " "; test(args...); } typedef long long ll; typedef pair pii; typedef pair pll; const int MAXN = (int)1e5 + 10; const int MOD = 998244353; const int INF = 1e9; int fa[MAXN], du[MAXN]; int fifa(int x) { if (fa[x] == x) return x; return fa[x] = fifa(fa[x]); } void Main() { int n, s; cin >> n >> s; for (int i = 1; i <=n; i++) fa[i] = i, du[i] = 0; vector ve; int cnt0 = 0; for (int i = 1; i < n; i++) { string s; cin >> s; for (int j = 0; j < i; j++) { if (s[j] == '0') { du[i + 1]++; du[j + 1]++; fa[fifa(i + 1)] = fifa(j + 1); cnt0++; } } } vector a; for (int i = 1; i <= n; i++) if (du[i]) a.push_back(i); int cnt = 0, num = 0; for (auto x : a) { if (du[x] & 1) cnt++; if (fifa(x) == x) num++; } int ans = -1; if (du[s] > 0 && du[s] % 2 == 1 && cnt == 2) { ans = cnt0 + (num - 1) * 2; } else if (du[s] == 0 && cnt == 0) { ans = cnt0 + (num - 1) * 2 + 2; } else if (du[s] > 0 && du[s] % 2 == 0 && cnt == 0) { ans = cnt0 + (num - 1) * 2; } cout << ans << "\n"; } int main() { #ifdef BanFcc freopen("in.txt", "r", stdin); /// freopen("out.txt", "w", stdout); #else ios_base:: sync_with_stdio(false); cin.tie(0); cout.tie(0); cout << fixed << setprecision(10); #endif int T = 1; cin >> T; for (int ca = 1; ca <= T; ca++) { // cout << "Case #" << ca << ": "; Main(); } return 0; }