#include using namespace std; typedef long long ll; const int N = 1e3 + 5; int father[N], degree[N], Size[N], n, s; string input[N]; int find(int x) { if (x == father[x]) return x; return father[x] = find(father[x]); } void mix(int x, int y) { int fx = find(x); int fy = find(y); if (fx != fy) { Size[father[y]] += Size[father[x]]; father[father[x]] = father[y]; } } void init(int n) { for (int i = 0; i <= n; i++) Size[i] = 1; for (int i = 0; i <= n; i++) father[i] = i; for (int i = 0; i <= n; i++) degree[i] = 0; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &s); init(n); for (int i = 1; i < n; i++) cin >> input[i]; int temp = 0, ans = 0; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (input[i][j] == '0') { degree[i]++, degree[j]++; ans++; mix(i, j); } } } for (int i = 0; i < n; i++) if (degree[i] & 1) temp++; s -= 1; if (temp > 2 || temp == 2 && degree[s] % 2 == 0) { puts("-1"); continue; } int tot = 0; for (int i = 0; i < n; i++) if (father[i] == i && Size[i] > 1) tot++; if (Size[find(s)] == 1) tot++; if (tot) ans += (tot - 1) * 2; cout << ans << endl; } return 0; }