1829E - The Lakes - CodeForces Solution


dfs and similar dsu graphs implementation

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ld double
#define vi  vector<int>
#define vvi vector<vi>
#define pii pair<int,int>
#define vpii vector<pair<int,int>>
#define all(v) v.begin(),v.end()
#define eb emplace_back
#define endl '\n'
const int M=1e9+7;
const ld eps = 1e-9;
const int INF=1e17;
int dfs(vvi &matrix,vvi& vis,int i,int j,int n, int m){
    vis[i][j]=1;
    int cs=matrix[i][j];
    int dx[]={1,-1,0,0};
    int dy[]={0,0,1,-1};
    for(int k=0;k<4;k++){
        int nx=dx[k]+i;
        int ny=dy[k]+j;
        if(nx>=0 && nx<n && ny>=0 && ny<m && matrix[nx][ny]>0 && !vis[nx][ny]){
            int sc=dfs(matrix,vis,nx,ny,n,m);
            cs+=sc;
        }
    }
    return cs;
}
void solve()
{  
    int n,m;
    cin>>n>>m;
    vvi a(n,vi(m));
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++) cin>>a[i][j];
    }    
    vvi vis(n,vi(m,0));
    int largest=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(!vis[i][j] && a[i][j]>0){
                int sz=dfs(a,vis,i,j,n,m);
                largest=max(largest,sz);
            }
        }
    }
    cout<<largest<<'\n';
}
int32_t main() 
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);

    int ff=1;
    std::cin>>ff;
    while(ff--)
        solve();
    return 0;
 
}


Comments

Submit
0 Comments
More Questions

1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General
1106A - Lunar New Year and Cross Counting
58A - Chat room
230A - Dragons
200B - Drinks
13A - Numbers
129A - Cookies
1367B - Even Array
136A - Presents
1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum