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 fdca4b4

Browse files
feat: add swift implementation to lcof2 problem: No.105 (doocs#3618)
1 parent 780e670 commit fdca4b4

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

‎lcof2/剑指 Offer II 105. 岛屿的最大面积/README.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,50 @@ impl Solution {
250250
}
251251
```
252252

253+
#### Swift
254+
255+
```swift
256+
class Solution {
257+
private var m = 0
258+
private var n = 0
259+
private var grid: [[Int]] = []
260+
261+
func maxAreaOfIsland(_ grid: [[Int]]) -> Int {
262+
self.m = grid.count
263+
self.n = grid[0].count
264+
self.grid = grid
265+
var maxArea = 0
266+
267+
for i in 0..<m {
268+
for j in 0..<n {
269+
maxArea = max(maxArea, dfs(i, j))
270+
}
271+
}
272+
273+
return maxArea
274+
}
275+
276+
private func dfs(_ i: Int, _ j: Int) -> Int {
277+
if grid[i][j] == 0 {
278+
return 0
279+
}
280+
281+
var area = 1
282+
grid[i][j] = 0
283+
let dirs = [-1, 0, 1, 0, -1]
284+
285+
for k in 0..<4 {
286+
let x = i + dirs[k], y = j + dirs[k + 1]
287+
if x >= 0 && x < m && y >= 0 && y < n {
288+
area += dfs(x, y)
289+
}
290+
}
291+
292+
return area
293+
}
294+
}
295+
```
296+
253297
<!-- tabs:end -->
254298

255299
<!-- solution:end -->
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
private var m = 0
3+
private var n = 0
4+
private var grid: [[Int]] = []
5+
6+
func maxAreaOfIsland(_ grid: [[Int]]) -> Int {
7+
self.m = grid.count
8+
self.n = grid[0].count
9+
self.grid = grid
10+
var maxArea = 0
11+
12+
for i in 0..<m {
13+
for j in 0..<n {
14+
maxArea = max(maxArea, dfs(i, j))
15+
}
16+
}
17+
18+
return maxArea
19+
}
20+
21+
private func dfs(_ i: Int, _ j: Int) -> Int {
22+
if grid[i][j] == 0 {
23+
return 0
24+
}
25+
26+
var area = 1
27+
grid[i][j] = 0
28+
let dirs = [-1, 0, 1, 0, -1]
29+
30+
for k in 0..<4 {
31+
let x = i + dirs[k], y = j + dirs[k + 1]
32+
if x >= 0 && x < m && y >= 0 && y < n {
33+
area += dfs(x, y)
34+
}
35+
}
36+
37+
return area
38+
}
39+
}

0 commit comments

Comments
(0)

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