@@ -170,6 +170,81 @@ public:
170
170
171
171
# 其它语言版本
172
172
173
+ ## Python
174
+ ### BFS
175
+ ```python
176
+ class Solution:
177
+ def __init__(self):
178
+ self.count = 0
179
+
180
+ def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
181
+ # 与200.独立岛屿不同的是:此题grid列表内是int!!!
182
+
183
+ # BFS
184
+ if not grid: return 0
185
+
186
+ m, n = len(grid), len(grid[0])
187
+ visited = [[False for i in range(n)] for j in range(m)]
188
+
189
+ result = 0
190
+ for i in range(m):
191
+ for j in range(n):
192
+ if not visited[i][j] and grid[i][j] == 1:
193
+ # 每一个新岛屿
194
+ self.count = 0
195
+ print(f'{self.count}')
196
+ self.bfs(grid, visited, i, j)
197
+ result = max(result, self.count)
198
+
199
+ return result
200
+
201
+ def bfs(self, grid, visited, i, j):
202
+ self.count += 1
203
+ visited[i][j] = True
204
+
205
+ queue = collections.deque([(i, j)])
206
+ while queue:
207
+ x, y = queue.popleft()
208
+ for new_x, new_y in [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1)]:
209
+ if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]) and not visited[new_x][new_y] and grid[new_x][new_y] == 1:
210
+ visited[new_x][new_y] = True
211
+ self.count += 1
212
+ queue.append((new_x, new_y))
213
+ ```
214
+ ### DFS
215
+ ``` python
216
+ class Solution :
217
+ def __init__ (self ):
218
+ self .count = 0
219
+
220
+ def maxAreaOfIsland (self , grid : List[List[int ]]) -> int :
221
+ # DFS
222
+ if not grid: return 0
223
+
224
+ m, n = len (grid), len (grid[0 ])
225
+ visited = [[False for _ in range (n)] for _ in range (m)]
226
+
227
+ result = 0
228
+ for i in range (m):
229
+ for j in range (n):
230
+ if not visited[i][j] and grid[i][j] == 1 :
231
+ self .count = 0
232
+ self .dfs(grid, visited, i, j)
233
+ result = max (result, self .count)
234
+ return result
235
+
236
+ def dfs (self , grid , visited , x , y ):
237
+ if visited[x][y] or grid[x][y] == 0 :
238
+ return
239
+ visited[x][y] = True
240
+ self .count += 1
241
+ for new_x, new_y in [(x + 1 , y), (x - 1 , y), (x, y + 1 ), (x, y - 1 )]:
242
+ if 0 <= new_x < len (grid) and 0 <= new_y < len (grid[0 ]):
243
+ self .dfs(grid, visited, new_x, new_y)
244
+ ```
245
+
246
+
247
+
173
248
## Java
174
249
175
250
这里使用深度优先搜索 DFS 来完成本道题目。我们使用 DFS 计算一个岛屿的面积,同时维护计算过的最大的岛屿面积。同时,为了避免对岛屿重复计算,我们在 DFS 的时候对岛屿进行 “淹没” 操作,即将岛屿所占的地方置为 0。
@@ -199,4 +274,4 @@ public int dfs(int[][] grid,int i,int j){
199
274
dfs(grid,i,j + 1 ) +
200
275
dfs(grid,i,j - 1 );
201
276
}
202
- ```
277
+ ```
0 commit comments