Count Sub Islands LeetCode solution in Python
1class Solution(object):2def countSubIslands(self, grid1, grid2):3m = len(grid1)4n = len(grid1[0])56def dfs(i, j):7if i < 0 or i >= m or j < 0 or j >= n or grid2[i][j] == 0:8return9grid2[i][j] = 010dfs(i + 1, j)11dfs(i - 1, j)12dfs(i, j + 1)13dfs(i, j - 1)1415# here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed16for i in range(m):17for j in range(n):18if grid2[i][j] == 1 and grid1[i][j] == 0:19dfs(i, j)20# now we just need to count the islands left over21count = 022for i in range(m):23for j in range(n):24if grid2[i][j] == 1:2526dfs(i, j)27count += 128return count