#include using namespace std; const int MAX = 1003; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, -1, 1}; int a[MAX][MAX]; int vis[MAX][MAX]; vector>> vals; int main() { #ifndef ONLINE_JUDGE freopen("inp.txt", "r", stdin); #endif ios_base::sync_with_stdio(false); int t, n, m; cin >> t; while(t--) { cin >> n >> m; vals.clear(); for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { cin >> a[i][j]; vis[i][j] = 0; vals.push_back({a[i][j], {i, j}}); } } sort(vals.rbegin(), vals.rend()); int ans = 0; for(auto it : vals) { if (vis[it.second.first][it.second.second]) { continue; } // cout << it.first << " : " << it.second.first << " " << it.second.second << "\n"; ans += 1; queue> q; vis[it.second.first][it.second.second] = 1; q.push({it.second.first, it.second.second}); while(!q.empty()) { pair u = q.front(); q.pop(); for(int i = 0; i < 4; ++i) { int x = dx[i] + u.first; int y = dy[i] + u.second; if (x >= 1 && x <= n && y >= 1 && y <= m) { if (!vis[x][y] && a[x][y] <= a[u.first][u.second]) { vis[x][y] = 1; q.push({x, y}); } } } } } cout << ans << "\n"; } return 0; }