intup(int x) { if (x - 1 <= 0) return x - 1 + n; elsereturn x - 1; }
intdown(int x) { if (x + 1 > n) return x + 1 - n; elsereturn x + 1; }
intleft(int x) { if (x - 1 <= 0) return x - 1 + n; elsereturn x - 1; }
intright(int x) { if (x + 1 > n) return x + 1 - n; elsereturn x + 1; }
intmain() { int T;
cin >> T; while (T--) { cin >> n >> k; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { cin >> g[i][j]; src[i][j] = g[i][j]; }
bool flag = true; for (int m = 1; m <= k; m++) { flag = true; len = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { int cnt = 0; if (g[left(i)][j] == 1) cnt++; if (g[left(i)][up(j)] == 1) cnt++; if (g[left(i)][down(j)] == 1) cnt++; if (g[right(i)][j] == 1) cnt++; if (g[right(i)][up(j)] == 1) cnt++; if (g[right(i)][down(j)] == 1) cnt++; if (g[i][up(j)] == 1) cnt++; if (g[i][down(j)] == 1) cnt++;
if (cnt == 3 && g[i][j] == 0) tmp[len++] = { i, j }; if (g[i][j] == 1 && cnt > 3 || g[i][j] == 1 && cnt < 2) tmp[len++] = { i, j }; } }
for (int i = 0; i < len; i++) { int x = tmp[i].first, y = tmp[i].second; g[x][y] = !g[x][y]; }
for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (g[i][j] != src[i][j]) { flag = false; break; } } if (!flag) break; } if (flag) { cout << "YES" << endl << m << endl; break; } }