Question Link - CodeChef: Practical coding for everyone
I am solving this problem with the help of BFS. But it is giving TLE. Can please help me to find what is the problem with my code.
int dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
bool isInside(int nx, int ny, int n, int m) {
if(nx < 0 || nx >= n || ny < 0 || ny >= m) {
return false;
}
return true;
}
int findIsland(int x, int y, int n, int m, vector<vector<int>> mat, vector<vector<bool>>& vis) {
int count = 1;
queue<pair<int, int>> q;
q.push({x, y});
vis[x][y] = true;
while(!q.empty()) {
pair<int, int> ele = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = ele.first + dir[i][0];
int ny = ele.second + dir[i][1];
if(isInside(nx, ny, n, m) && mat[nx][ny] == 1 && !vis[nx][ny]) {
vis[nx][ny] = true;
count++;
q.push({nx, ny});
}
}
}
return count;
}
void solve() {
int n, m;
cin >> n >> m;
vector<string> temp(n);
for(int i = 0; i < n; i++) {
cin >> temp[i];
}
//cout << n << " " << m << endl;
vector<vector<int>> mat(n, vector<int>(m, 0));
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
mat[i][j] = temp[i][j] - '0';
}
}
vector<int> arr;
vector<vector<bool>> vis(n, vector<bool>(m, false));
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mat[i][j] == 1 && vis[i][j] == false) {
int island = findIsland(i, j, n, m, mat, vis);
arr.push_back(island);
}
}
}
sort(arr.begin(), arr.end());
reverse(arr.begin(), arr.end());
int ans = 0;
for(int i = 1; i < (int)arr.size(); i+=2) {
ans += arr[i];
}
cout << ans << endl;
}