1
+ '''
2
+ Author: fghpdf
3
+ Date: 2021-10-09 12:21:19
4
+ LastEditTime: 2021-10-09 12:41:38
5
+ LastEditors: fghpdf
6
+ '''
7
+ from typing import List
8
+ import unittest
9
+
10
+ class Solution :
11
+ def maxAreaOfIsland (self , grid : List [List [int ]]) -> int :
12
+ if (len (grid ) == 0 or len (grid [0 ]) == 0 ):
13
+ return 0
14
+
15
+ maxArea = 0
16
+ for i in range (len (grid )):
17
+ for j in range (len (grid [i ])):
18
+ if grid [i ][j ] == 1 :
19
+ area = self .backtrack (grid , i , j , 0 )
20
+ maxArea = max (maxArea , area )
21
+
22
+ return maxArea
23
+
24
+ def backtrack (self , grid , row , col , area ) -> int :
25
+ # edge is end
26
+ if (row < 0 or row >= len (grid ) or (col < 0 or col >= len (grid [row ]))):
27
+ return area
28
+
29
+ # sea 0 is end
30
+ if grid [row ][col ] == 0 :
31
+ return area
32
+
33
+ # island area +1
34
+ if grid [row ][col ] == 1 :
35
+ area += 1
36
+ grid [row ][col ] = 0 # visited
37
+
38
+ # left
39
+ area = self .backtrack (grid , row , col - 1 , area )
40
+ # up
41
+ area = self .backtrack (grid , row - 1 , col , area )
42
+ # right
43
+ area = self .backtrack (grid , row , col + 1 , area )
44
+ # down
45
+ area = self .backtrack (grid , row + 1 , col , area )
46
+
47
+ return area
48
+
49
+
50
+
51
+ class TestMaxAreaOfIsland (unittest .TestCase ):
52
+ def test_max_area_of_island (self ):
53
+ sol = Solution ()
54
+ self .assertEqual (sol .maxAreaOfIsland ([
55
+ [0 ,0 ,1 ,0 ,0 ,0 ,0 ,1 ,0 ,0 ,0 ,0 ,0 ],
56
+ [0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,0 ,0 ,0 ],
57
+ [0 ,1 ,1 ,0 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ],
58
+ [0 ,1 ,0 ,0 ,1 ,1 ,0 ,0 ,1 ,0 ,1 ,0 ,0 ],
59
+ [0 ,1 ,0 ,0 ,1 ,1 ,0 ,0 ,1 ,1 ,1 ,0 ,0 ],
60
+ [0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,0 ,0 ],
61
+ [0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,0 ,0 ,0 ],
62
+ [0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,0 ,0 ,0 ,0 ]]), 6 )
63
+ self .assertEqual (sol .maxAreaOfIsland ([[0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ]]), 0 )
64
+
65
+ if __name__ == '__main__' :
66
+ unittest .main ()
0 commit comments