I'm trying to solve the problem "Islands" of the following contest
This is my simple BFS solution, which produces a runtime error on testcase 21. Does anybody have an explanation?
include
include
using namespace std;
void check_position(int i, int k, char** grid, queue<pair<int,int> >& q){ if(grid[i][k]=='L' || grid[i][k]=='C'){ grid[i][k] = 'X'; q.push(pair<int,int>(i,k)); } }
void bfs(int i, int k, char** grid, int n, int m){ queue<pair<int,int> > q; grid[i][k]='X'; q.push(pair<int,int>(i,k)); pair<int,int> temp; while(!q.empty()){ temp = q.front(); q.pop(); if (temp.first>0) check_position(temp.first-1,temp.second, grid, q); if (temp.second>0) check_position(temp.first,temp.second-1, grid, q); if (temp.second<m-1) check_position(temp.first,temp.second+1, grid, q); if (temp.first<n-1) check_position(temp.first+1,temp.second, grid, q); } }
int main(){ int n,m; cin>>n>>m; char** grid = new char* [n]; for (int i=0;i<n;i++) grid[i] = new char[m]; for (int i=0;i<n;i++) cin>>grid[i]; int island_count = 0; for (int i=0;i<n;i++){ for (int k=0;k<m;k++){ if (grid[i][k]=='L'){ island_count++; bfs(i,k,grid,n,m); } } } cout<<island_count<<"\n"; }



