I am getting WA in 1, 3, and 4 cases. Please help.
#include
#include
#include
#include
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
bool inside(int i, int j, int n, int m){
return(i >= 0 and j >= 0 and i < n and j < m );
}
bool visited(int i, int j, string *m){
if(m[i][j] != ‘v’){
return false;
}
else{
return true;
}
}
bool isLand(int i, int j, string *m){
return(m[i][j] == ‘1’);
}
ll bfs(int k, int l, int r, int c, string *m){
queue <pair<int,int>> q;
ll count = 0;
if(!visited(k,l,m)){
q.push({k,l});
m[k][l] = ‘v’;
}
while(!q.empty()){
//up
pair <int,int> p = q.front();
q.pop();
count++;
int i = p.first;
int j = p.second;
if(inside(i-1,j,r,c) and isLand(i-1,j,m)){
q.push({i-1,j});
m[i-1][j] = ‘v’;
count++;
}
//right
if(inside(i,j+1,r,c) and isLand(i,j+1,m)){
q.push({i,j+1});
m[i][j+1] = ‘v’;
count++;
}
//down
if(inside(i+1,j,r,c) and isLand(i+1,j,m)){
q.push({i+1,j});
m[i+1][j] = ‘v’;
count++;
}
//left
if(inside(i,j-1,r,c) and isLand(i,j-1,m)){
q.push({i,j-1});
m[i][j-1] = ‘v’;
count++;
}
}
return count;
}
int main() {
int t;
cin >> t;
while(t–){
int n,m;
cin >> n >> m;
string mape[n];
for(int i=0;i<n;i++){
cin >> mape[i];
}
std::vector lands;
for(int i =0; i<n;i++){
for(int j=0;j<m;j++){
if(mape[i][j] == '1'){
lands.push_back(bfs(i,j,n,m,mape));
}
}
}
sort(lands.begin(), lands.end(), greater<int>());
ll chef_land = 0;
for(int i=1;i<lands.size();i+=2){
chef_land += lands[i];
}
cout << chef_land << endl;
}
return 0;
}