Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 47975cf

Browse files
authored
Create Max_Area_of_Island.py
1 parent 1a07c65 commit 47975cf

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /