Advertisement
imashutosh51

Find the number of islands

Jul 31st, 2022 (edited)
54
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. def feasible(grid,i,j):
  2.     if i>=0 and j>=0 and i<len(grid) and j<len(grid[0]) and grid[i][j]=='L':
  3.         return True
  4.     return False
  5.    
  6. def dfs(grid,i,j,visited):
  7.     x = [-1, -1,  0, 1, 1,  1,  0, -1]
  8.     y = [ 0,  1,  1, 1, 0, -1, -1, -1]
  9.     for k in range(8):
  10.         i_new=i+x[k]
  11.         j_new=j+y[k]
  12.         if feasible(grid,i_new,j_new) and visited[i_new][j_new]==0:
  13.             visited[i_new][j_new]=1
  14.             dfs(grid,i_new,j_new,visited)
  15.    
  16.    
  17. class Solution:
  18.     def numIslands(self, grid):
  19.         r=len(grid)
  20.         c=len(grid[0])
  21.         visited=[[0]*c for i in range(r)]
  22.         count=0
  23.         for i in range(r):
  24.             for j in range(c):
  25.                 if visited[i][j]==0 and grid[i][j]=='L':
  26.                     visited[i][j]=1
  27.                     dfs(grid,i,j,visited)
  28.                     count+=1
  29.         return count
  30.        
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement