Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.9 kB
0
Indexable
Never
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define endl "\n"
 
const double PI = 3.14159265358979;
const ll INF =  1e18 + 7;
const ll MOD = 1e9 + 7;
const ll nax = 100005;
const int LOG = 25;

int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int n, m;


void dfs(int i, int j, vector<vector<int> > &matrix, vector<vector<int> > &component, int groupId, int &groupSize) {
    component[i][j] = groupId;
    groupSize++;

    for (int k = 0; k < 4; k++) {
        int x = i + dx[k];
        int y = j + dy[k];
        if (x >= 0 && x < n && y >= 0 && y < m && matrix[x][y] == 0 && component[x][y] == 0) {
            dfs(x, y, matrix, component, groupId, groupSize);
        }
    }
}

void solve() {
    cin >> n >> m;
    vector<vector<int> > matrix(n, vector<int> (m));
    vector<vector<int> > component(n, vector<int> (m, 0));

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> matrix[i][j];
        }
    }

    int groupId = 0, groupSize = 0;
    map<int, int> groupSizeById;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] || component[i][j]) continue;
            groupId++;
            groupSize = 0;
            dfs(i, j, matrix, component, groupId, groupSize);
            groupSizeById[groupId] = groupSize;
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] || groupSizeById[component[i][j]] == 1) continue;
            matrix[i][j] = groupSizeById[component[i][j]];
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int t; cin >> t; while(t--)
    solve();
    return 0;
}
Leave a Comment