Skip to content

Commit 4a31fd5

Browse files
committed
feat: Add solution for LeetCode problem 200
1 parent 53e58a1 commit 4a31fd5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

number-of-islands/WhiteHyun.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//
2+
// 200. Number of Islands
3+
// https://leetcode.com/problems/number-of-islands/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/28.
7+
//
8+
9+
class Solution {
10+
func numIslands(_ grid: [[Character]]) -> Int {
11+
var visited: [[Bool]] = .init(
12+
repeating: .init(repeating: false, count: grid[0].count),
13+
count: grid.count
14+
)
15+
var islands = 0
16+
17+
for row in 0 ..< grid.count {
18+
for col in 0 ..< grid[row].count where grid[row][col] == "1" && !visited[row][col] {
19+
visited[row][col] = true
20+
dfs(grid, &visited, row, col)
21+
islands += 1
22+
}
23+
}
24+
25+
return islands
26+
}
27+
28+
private func dfs(
29+
_ grid: [[Character]],
30+
_ visited: inout [[Bool]],
31+
_ x: Int,
32+
_ y: Int
33+
) {
34+
for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
35+
let nx = dx + x
36+
let ny = dy + y
37+
guard grid.indices ~= nx,
38+
grid[x].indices ~= ny,
39+
visited[nx][ny] == false,
40+
grid[nx][ny] == "1"
41+
else {
42+
continue
43+
}
44+
visited[nx][ny] = true
45+
dfs(grid, &visited, nx, ny)
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)