# Number of Islands in Python

PythonServer Side ProgrammingProgramming

Suppose we have a grid, there are few 0s and few 1s. We have to count the number of islands. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water.

Suppose the grid is like −

 1 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 1 1

There are three islands.

To solve this, we will follow these steps −

• There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −
• if number of rows in the grid is 0, then return 0
• n = row count and m := column count, and ans := 0
• for i in range 0 to n – 1
• for j in range 0 to m
• if grid[i, j] = 1, then ans := ans + 1
• makeWater(i, j, n, m, grid)
• the makeWater() will take the indices i, j, row and col count n and m, and grid
• if i <0 or j < 0 or i >= n or j >= m, then return from this method
• if grid[i, j] = 0, then return otherwise make grid[i, j] := 0
• call makeWater(i + 1, j, n, m, grid)
• call makeWater(i, j + 1, n, m, grid)

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution(object):
def numIslands(self, grid):
if len(grid) == 0:
return 0
n= len(grid)
m = len(grid[0])
ans = 0
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
ans+=1
self.make_water(i,j,n,m,grid)
return ans
def make_water(self,i,j,n,m,grid):
if i<0 or j<0 or i>=n or j>=m:
return
if grid[i][j] == "0":
return
else:
grid[i][j]="0"
self.make_water(i+1,j,n,m,grid)
self.make_water(i,j+1,n,m,grid)
self.make_water(i-1,j,n,m,grid)
self.make_water(i,j-1,n,m,grid)
ob1 = Solution()
print(ob1.numIslands([["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],
["0","0","0","1","1"]]))

## Input

[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]

## Output

3
Updated on 04-May-2020 08:57:19