Okay I am attaching the code here.
TLE ONE-
class Solution {
public:
int n,m;
bool isvalid(int r,int c)
{
if(r<0 or c<0 or r>n-1 or c>m-1)
return false;
return true;
}
int numIslands(vector<vector<char>>& grid)
{
if(grid.empty() or grid[0].empty())
return 0;
n=grid.size();
m=grid[0].size();
int islands=0;
pair<int,int> moves[4]={{0,1},{1,0},{-1,0},{0,-1}};
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++){
if(grid[i][j]=='1')
{
islands++;
queue<pair<int,int>> q;
q.push({i,j});
while(!q.empty())
{
pair<int,int> p=q.front();
grid[p.first][p.second]='0';
q.pop();
for(auto x:moves)
{
if(isvalid(p.first+x.first,p.second+x.second) and grid[p.first+x.first][p.second+x.second]=='1'){
q.push({p.first+x.first,p.second+x.second});
}
}
}
}
}
}
return islands;
}
};
CORRECT ONE-
class Solution {
public:
int n,m;
bool isvalid(int r,int c)
{
if(r<0 or c<0 or r>n-1 or c>m-1)
return false;
return true;
}
int numIslands(vector<vector<char>>& grid)
{
if(grid.empty() or grid[0].empty())
return 0;
n=grid.size();
m=grid[0].size();
int islands=0;
pair<int,int> moves[4]={{0,1},{1,0},{-1,0},{0,-1}};
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++){
if(grid[i][j]=='1')
{
islands++;
queue<pair<int,int>> q;
q.push({i,j});
grid[i][j]='0';
while(!q.empty())
{
pair<int,int> p=q.front();
q.pop();
for(auto x:moves)
{
if(isvalid(p.first+x.first,p.second+x.second) and grid[p.first+x.first][p.second+x.second]=='1'){
q.push({p.first+x.first,p.second+x.second});
grid[p.first+x.first][p.second+x.second]='0';
}
}
}
}
}
}
return islands;
}
};