fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define int long long int
  5. #define ld long double
  6. #define all(x) x.begin(), x.end()
  7. #define sortall(x) sort(all(x))
  8. #define endl '\n'
  9. #define yes cout<<"YES\n";
  10. #define no cout<<"NO\n";
  11. #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  12. /*
  13.  * Think twice, code once
  14.  * Think of different approaches to tackle a problem: write them down.
  15.  * Think of different views of the problem. don't look from only one side.
  16.  * don't get stuck in one approach.
  17.  * common mistakes: - over_flow
  18.  * - out_of_bound index
  19.  * - infinite loop
  20.  * - corner cases
  21.  * - duplication counting.
  22. */
  23.  
  24. void solve()
  25. {
  26. int n, m; cin >> n >> m;
  27. vector<vector<int>> v(n+2, vector<int>(m+2));
  28. for (int i = 1; i <= n; ++i)
  29. {
  30. for (int j = 1; j <= m; ++j)
  31. {
  32. cin >> v[i][j];
  33. }
  34. }
  35. map<int, int> mp1;
  36. map<int, int> mp2;
  37. bool flag = false;
  38. int cnt = INT_MAX, num = 0;
  39. for (int i = 1; i <= n; ++i)
  40. {
  41. for (int j = 1; j <= m; ++j)
  42. {
  43. if (mp1.count(v[i][j]) == 0)
  44. {
  45. mp1[v[i][j]]++;
  46. }else
  47. {
  48. if (v[i][j] != v[i-1][j] && v[i][j] != v[i][j-1] && v[i][j] != v[i+1][j] && v[i][j] != v[i][j+1])
  49. {
  50. mp1[v[i][j]]++;
  51. }else
  52. {
  53. mp2[v[i][j]]++;
  54. }
  55. }
  56. }
  57. }
  58. for (auto&i:mp1)
  59. {
  60. // cout << i.first << ' ' << i.second << '\n';
  61. if (mp1.count(i.first) && mp2.count(i.first) )
  62. {
  63. num = i.first;
  64. cnt = i.second;
  65. flag = true;
  66. }
  67. }
  68. int ans = 0;
  69. if (flag)
  70. {
  71. for (auto&i:mp1)
  72. {
  73. if (i.first != num)
  74. ans++;
  75. }
  76. for (auto&i:mp2)
  77. {
  78. if (i.first != num)
  79. ans++;
  80. }
  81. cout << ans;
  82. }else
  83. {
  84. for (auto&i:mp1)
  85. {
  86. if (i.first != num)
  87. ans++;
  88. }
  89. for (auto&i:mp2)
  90. {
  91. if (i.first != num)
  92. ans++;
  93. }
  94. cout << ans-1;
  95. }
  96. }
  97.  
  98. int32_t main()
  99. {
  100. // fast
  101. int t = 1;
  102. cin >> t;
  103. while (t--)
  104. {
  105. solve();
  106. if (t) cout << '\n';
  107. }
  108. cout << '\n';
  109. return 0;
  110. }
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
-1