class Solution {
public:
int numIslands(vector<vector<char>> &grid) {
int m = grid.size();
if (m==0) return 0;
int n = grid[0].size();
int count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j]=='1') {
helper(grid,i,j,m,n);
count++;
}
}
}
return count;
}
void helper(vector<vector<char> >& a, int i, int j, int m, int n) {
a[i][j] = 0;
if (i > 0 && a[i1][j]=='1') helper(a,i1,j,m,n);
if (j > 0 && a[i][j1]=='1') helper(a,i,j1,m,n);
if (i < m1 && a[i+1][j]=='1') helper(a,i+1,j,m,n);
if (j < n1 && a[i][j+1]=='1') helper(a,i,j+1,m,n);
}
};
Simple c++ dfs solution


Here is python version with similar thought:
def destroy_island(self, grid, visited, i, j, h, w): # burn current spot visited.add((i, j)) # burn to four directions if i1 >= 0 and grid[i  1][j] == "1" and (i  1, j) not in visited: self.destroy_island(grid, visited, i  1, j, h, w) if j1 >= 0 and grid[i][j  1] == "1" and (i, j  1) not in visited: self.destroy_island(grid, visited, i, j  1, h, w) if i+1 < h and grid[i + 1][j] == "1" and (i + 1, j) not in visited: self.destroy_island(grid, visited, i + 1, j, h, w) if j+1 < w and grid[i][j + 1] == "1" and (i, j + 1) not in visited: self.destroy_island(grid, visited, i, j + 1, h, w) def numIslands(self, grid): if not grid: return 0 visited = set() counter = 0 n = len(grid) m = len(grid[0]) for i in xrange(n): for j in xrange(m): if grid[i][j] == "1" and (i, j) not in visited: counter += 1 self.destroy_island(grid, visited, i, j, n, m) return counter