Skip to content

Commit 8ca1631

Browse files
committed
feat: 695 Max Area of Island
1 parent bdfc158 commit 8ca1631

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

create_py_solution.sh

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
###
2+
# @Author: fghpdf
3+
# @Date: 2021-10-09 12:05:55
4+
# @LastEditTime: 2021-10-09 12:19:50
5+
# @LastEditors: fghpdf
6+
###
7+
8+
RED='\033[0;31m'
9+
NC='\033[0m' # No Color
10+
11+
problem_name=$1;
12+
problem_length=echo ${problem_name} | wc -l;
13+
14+
if [[ ${problem_length} -le 0 ]]; then
15+
echo "${RED} must input problem name ${NC} \n";
16+
fi
17+
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)