#include #define RAN(v) v.begin(), v.end() #define pb push_back #define lb lower_bound #define ub upper_bound using namespace std; typedef long long ll; template inline void upd1(T1& a, const T2& b) { a = a < b ? a : b; } template inline void upd2(T1& a, const T2& b) { a = b < a ? a : b; } ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } struct Ano { operator ll() { ll x = 0, y = 0, c = getchar(); while (c < 48) { y = c == 45; c = getchar(); } while (c > 47) { x = x*10 + c-48; c = getchar(); } return y ? -x : x; } } buf; const int N = 1005; char t[N]; int d[N], p[N], r[N]; inline int find(int i) { while (i != p[i]) { i = p[i] = p[p[i]]; } return i; } inline void join(int i, int j) { int u = find(i); int v = find(j); if (u != v) { p[u] = v; r[v] += r[u]; } } int main() { int q = buf; while (q--) { int n = buf, k = buf; fill_n(d + 1, n, 0); iota(p + 1, p + n + 1, 1); fill_n(r + 1, n, 1); int s = 0; for (int i = 2; i <= n; ++i) { scanf("%s", t + 1); for (int j = 1; j < i; ++j) if (t[j] == '0') { ++d[i]; ++d[j]; ++s; join(i, j); } } int c[2] = {0}; for (int i = 1; i <= n; ++i) { ++c[d[i] & 1]; } if (c[1] != 0 && (c[1] != 2 || ~d[k] & 1)) { s = -1; } else { for (int i = 1; i <= n; ++i) if (i == p[i] && i != find(k) && r[i] != 1) { s += 2; } } printf("%d\n", s); } }