#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long int
#define ld long double
#define all(x) x.begin(), x.end()
#define sortall(x) sort(all(x))
#define endl '\n'
#define yes cout<<"YES\n";
#define no cout<<"NO\n";
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
/*
 * Think twice, code once
 * Think of different approaches to tackle a problem: write them down.
 * Think of different views of the problem. don't look from only one side.
 * don't get stuck in one approach.
 * common mistakes: - over_flow
 *                  - out_of_bound index
 *                  - infinite loop
 *                  - corner cases
 *                  - duplication counting.
*/

void solve()
{
    int n, m; cin >> n >> m;
    vector<vector<int>> v(n+2, vector<int>(m+2));
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= m; ++j)
        {
            cin >> v[i][j];
        }
    }
    map<int, int> mp1;
    map<int, int> mp2;
    bool flag = false;
    int cnt = INT_MAX, num = 0;
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= m; ++j)
        {
            if (mp1.count(v[i][j]) == 0)
            {
                mp1[v[i][j]]++;
            }else
            {
                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])
                {
                    mp1[v[i][j]]++;
                }else
                {
                    mp2[v[i][j]]++;
                }
            }
        }
    }
    for (auto&i:mp1)
    {
        // cout << i.first << ' ' << i.second << '\n';
        if (mp1.count(i.first) && mp2.count(i.first) )
        {
            num = i.first;
            cnt = i.second;
            flag = true;
        }
    }
    int ans = 0;
    if (flag)
    {
        for (auto&i:mp1)
        {
            if (i.first != num)
                ans++;
        }
        for (auto&i:mp2)
        {
            if (i.first != num)
                ans++;
        }
        cout << ans;
    }else
    {
        for (auto&i:mp1)
        {
            if (i.first != num)
                ans++;
        }
        for (auto&i:mp2)
        {
            if (i.first != num)
                ans++;
        }
        cout << ans-1;
    }
}

int32_t main()
{
    // fast
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
        if (t) cout << '\n';
    }
    cout << '\n';
    return 0;
}