int A[100][100]; int tmp[100][100]; int n, m, k; inline int INF = 1000; inline void count1(int row, int col){ int cnt = 0; for (int i = 0; i < n; ++i) tmp[i][col] = A[i][col]; for (int j = 0; j < m; ++j) tmp[row][j] = A[row][j]; for (int i = row - 1; i >= 0; --i) for (int j = col - 1; j >= 0; --j){ if (tmp[i + 1][j + 1] == tmp[i + 1][j] && tmp[i][j + 1] == tmp[i + 1][j]) tmp[i][j] = tmp[i + 1][j]; else if (tmp[i + 1][j] == tmp[i + 1][j + 1]) tmp[i][j] = tmp[i][j + 1]; else if (tmp[i][j + 1] == tmp[i + 1][j + 1]) tmp[i][j] = tmp[i + 1][j]; else tmp[i][j] = tmp[i + 1][j + 1]; if (tmp[i][j] != A[i][j]) ++cnt; if (cnt > k) return INF; } for (int i = row - 1; i >= 0; --i) for (int j = col + 1; j < m; ++j){ if (tmp[i + 1][j - 1] == tmp[i + 1][j] && tmp[i][j - 1] == tmp[i + 1][j]) tmp[i][j] = tmp[i + 1][j]; else if (tmp[i + 1][j] == tmp[i + 1][j - 1]) tmp[i][j] = tmp[i][j - 1]; else if (tmp[i][j - 1] == tmp[i + 1][j - 1]) tmp[i][j] = tmp[i + 1][j]; else tmp[i][j] = tmp[i + 1][j - 1]; if (tmp[i][j] != A[i][j]) ++cnt; if (cnt > k) return INF; } for (int i = row + 1; i < n; ++i) for (int j = col - 1; j >= 0; --j){ if (tmp[i - 1][j + 1] == tmp[i - 1][j] && tmp[i][j + 1] == tmp[i - 1][j]) tmp[i][j] = tmp[i - 1][j]; else if (tmp[i - 1][j] == tmp[i - 1][j + 1]) tmp[i][j] = tmp[i][j + 1]; else if (tmp[i][j + 1] == tmp[i - 1][j + 1]) tmp[i][j] = tmp[i - 1][j]; else tmp[i][j] = tmp[i + 1][j + 1]; if (tmp[i][j] != A[i][j]) ++cnt; if (cnt > k) return INF; } for (int i = row + 1; i < n; ++i) for (int j = col + 1; j < m; ++j){ if (tmp[i - 1][j - 1] == tmp[i - 1][j] && tmp[i][j - 1] == tmp[i - 1][j]) tmp[i][j] = tmp[i - 1][j]; else if (tmp[i - 1][j] == tmp[i - 1][j - 1]) tmp[i][j] = tmp[i][j - 1]; else if (tmp[i][j - 1] == tmp[i - 1][j - 1]) tmp[i][j] = tmp[i - 1][j]; else tmp[i][j] = tmp[i - 1][j - 1]; if (tmp[i][j] != A[i][j]) ++cnt; if (cnt > k) return INF; } } inline void solve1(){ int ans = INF; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j){ int mb = count1(i, j); mn(ans, mb); } if (ans == INF) ans = -1; cout << ans << endl; }