1+ /* *CF2069B
2+ * For each colour, find out ifs doable in 1 or 2 moves (always doable in 2 moves via checkerboard style approach)
3+ */
4+ #pragma GCC optimize("Ofast")
5+ #pragma GCC optimize("unroll-loops")
6+ #include < bits/stdc++.h>
7+ using namespace std ;
8+
9+ #define fast_cin () \
10+ ios_base::sync_with_stdio (false ); \
11+ cin.tie(NULL ); \
12+ cout.tie(NULL );
13+
14+ int dr[] = {-1 , 1 , 0 , 0 };
15+ int dc[] = {0 , 0 , -1 , 1 };
16+
17+ int main () {
18+ fast_cin ();
19+ int t;
20+ cin >> t;
21+ while (t--) {
22+ int h, w;
23+ cin >> h >> w;
24+ vector<vector<int >> arr (h, vector<int >(w));
25+ for (int i = 0 ; i < h; ++i) {
26+ for (int j = 0 ; j < w; ++j) {
27+ cin >> arr[i][j];
28+ }
29+ }
30+
31+ unordered_map<int , bool > d;
32+
33+ for (int r = 0 ; r < h; ++r) {
34+ for (int c = 0 ; c < w; ++c) {
35+ int colour = arr[r][c];
36+ if (d[colour]) {
37+ continue ;
38+ }
39+
40+ for (int i = 0 ; i < 4 ; ++i) {
41+ int nr = r + dr[i];
42+ int nc = c + dc[i];
43+
44+ if (nr >= 0 && nr < h && nc >= 0 && nc < w) {
45+ if (arr[nr][nc] == colour) {
46+ d[colour] = true ;
47+ break ;
48+ }
49+ }
50+ }
51+ }
52+ }
53+
54+ vector<int > costs;
55+ for (const auto & pair : d) {
56+ costs.push_back (pair.second ? 2 : 1 );
57+ }
58+
59+ int total_cost = accumulate (costs.begin (), costs.end (), 0 );
60+ int max_cost = *max_element (costs.begin (), costs.end ());
61+ cout << total_cost - max_cost << endl;
62+ }
63+
64+ return 0 ;
65+ }
0 commit comments