Number of Islands — Day 5(Python)
By: Annamariya Tharayil
Tags: 365dayschallenge, Leetcode Medium, Graph, Python, Coding

An island is formed by connecting adjacent lands horizontally or vertically and is surrounded by water along the borders. According to the question, “0” signifies water, while the land signifies “1”.

If we consider the matrix as a collection of connected graphs, we might be able to come up with a solution. Let “1” be a node in the graph, now count the number of connected graphs. The resulting number will be our answer.

Let me convert the matrix to a graph.

Input: grid = [

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

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

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

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

]

Output: 3

Graph representation of the matrix

Now, count the number of connected graphs.

To find the number of islands, how about we use the same logic here?

Depth-First-Search

Depth-First-Search is a graph traversing algorithm that starts from the root and traverses as far as possible. Some of the application DFS can be to check the presence of a node in a graph, check for cycles in the graph. Let us see how DFS can be used to solve the given problem.

It is best practice not to mess with the input array, and hence we will define a boolean array initialized as False.

visited = [[False for col in range(len(grid[0]))]for row in range(len(grid))]

The above array will give us information about which island has been visited.

Analyze each element in the grid, if the given block is equal to “1” and if it is unvisited, then perform DFS.

count = 0

for row in range(len(grid)):

for col in range(len(grid[0])):

if(grid[row][col] == "1" and visited[row][col] == False):

self.dfs(row, col, visited, grid)

count += 1

Call the DFS function. Ensure that you mark the current block as visited. Make a list of neighbors possible for a block. In this case, we consider neighbors as 4-directional. Hence neighbors will be as follows.

visited[row][col] = True

valid_row = [-1, 0, 0, 1]

valid_col = [0, -1, 1, 0]

Add the above neighbors to the current block. Check if neighbors contain land and are unvisited, also don’t forget to check that new block fall within the limits of the grid.

def isSafe(self, grid, row, col, visited):

return(0<= row < len(grid) and

0 <= col < len(grid[0]) and

grid[row][col] == “1” and visited[row][col] == False)

If the above code is True, call the DFS function again.

The complete code snippet is as follows.

class Solution:

def isSafe(self, grid, row, col, visited):

return( 0<= row < len(grid) and

0 <= col < len(grid[0]) and

grid[row][col] == "1" and visited[row][col] == False)



def dfs(self, row, col, visited, grid):

valid_row = [-1, 0, 0, 1]

valid_col = [0, -1, 1, 0]

visited[row][col] = True

for neighbour in range(len(valid_row)):

new_row = row + valid_row[neighbour]

new_col = col + valid_col[neighbour]

if(self.isSafe(grid, new_row, new_col, visited)):

self.dfs(new_row, new_col, visited, grid)







def numIslands(self, grid: List[List[str]]) -> int:

visited = [[False for col in range(len(grid[0]))]for row in range(len(grid))]

count = 0

for row in range(len(grid)):

for col in range(len(grid[0])):

if(grid[row][col] == "1" and visited[row][col] == False):

self.dfs(row, col, visited, grid)

count += 1

return count

Complexity analysis.

Time Complexity

All the blocks will be visited only once and hence time complexity of the above code snippet is O(M*N) where M is the number of rows and N is the number of columns.

Space Complexity

We are creating a new array of size same as the old grid, and hence space complexity of the above code snippet is O(M*N) where M is the number of rows and N is the number of columns.