|
| 1 | +# DFS Solution - O(M*N) Time and O(1) Space |
| 2 | + |
| 3 | +class Solution: |
| 4 | + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: |
| 5 | + rows, cols = len(grid), len(grid[0]) |
| 6 | + ans = 0 |
| 7 | + def DFS(i, j, m): |
| 8 | + # Exit condition |
| 9 | + if i < 0 or j < 0 or i > rows-1 or j > cols-1 or m[i][j] == 0: |
| 10 | + return 0 |
| 11 | + # Mark the current node as visited |
| 12 | + if m[i][j] == 1: |
| 13 | + m[i][j] = 0 |
| 14 | + |
| 15 | + # N-4 Connectivity. Calling DFS on four neighbours |
| 16 | + x = DFS(i-1,j,m) |
| 17 | + y = DFS(i,j-1,m) |
| 18 | + z = DFS(i+1,j,m) |
| 19 | + t = DFS(i,j+1,m) |
| 20 | + |
| 21 | + sums = 1+x+y+z+t |
| 22 | + |
| 23 | + return sums |
| 24 | + |
| 25 | + # Calling DFS for every set Node |
| 26 | + for i in range(rows): |
| 27 | + for j in range(cols): |
| 28 | + if grid[i][j] == 1: |
| 29 | + curr = DFS(i,j,grid) |
| 30 | + ans = max(ans, curr) |
| 31 | + |
| 32 | + return ans |
0 commit comments