#include #include #include #include using namespace std; const int N = 1e3 + 100; int n, s, res; char str[N]; int cnt[N], fa[N]; int find(int x) { if (x == fa[x]) return x; return fa[x] = find(fa[x]); } void join(int a, int b) { a = find(a); b = find(b); if (a == b) return; fa[a] = b; } bool solve() { vector V; for (int i = 1; i <= n; i++) if (cnt[i] % 2) V.push_back(i); if (V.size() > 2) return false; if (V.size() == 2 && s != V[0] && s != V[1]) return false; int ans = res - 2; for (int i = 1; i <= n; i++) if (cnt[i] && i == find(i)) ans += 2; if (!cnt[s]) ans += 2; printf("%d\n", ans); return true; } int main() { //freopen("0.txt", "r", stdin); int T; scanf("%d", &T); while (T--) { scanf("%d%d", &n, &s); res = 0; for (int i = 1; i <= n; i++) fa[i] = i; for (int i = 2; i <= n; i++) { scanf("%s", str + 1); for (int j = 1; j < i; j++) { if (str[j] == '0') { cnt[i]++; cnt[j]++; join(i, j); res++; } } } if (!solve()) puts("-1"); memset(cnt, 0, sizeof(cnt)); } return 0; }