# Sharing my 20ms C++ solution (doing paint)

• ``````class Solution {
private:
void paint(vector<vector<char>>& grid, vector<vector<bool>>& visited, int i, int j)
{
int m = grid.size();
int n = grid[0].size();

if(grid[i][j]=='1')
{
visited[i][j] = true;
if(i-1>=0&&visited[i-1][j]==false&&grid[i-1][j]=='1')
paint(grid, visited, i-1, j);

if(i+1<m&&visited[i+1][j]==false&&grid[i+1][j]=='1')
paint(grid, visited, i+1, j);

if(j-1>=0&&visited[i][j-1]==false&&grid[i][j-1]=='1')
paint(grid, visited, i, j-1);

if(j+1<n&&visited[i][j+1]==false&&grid[i][j+1]=='1')
paint(grid, visited, i, j+1);
}
}

public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
if(m==0)
return 0;
int n = grid[0].size();
if(n==0)
return 0;

vector<vector<bool>> visited(m, vector<bool>(n, false));
int i, j, count=0;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
{
if(visited[i][j]==false && grid[i][j]=='1')
{
paint(grid, visited, i, j);
count++;
}
}

return count;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.