Skip to content

Commit 216f259

Browse files
authored
Merge pull request #846 from hereisderek/main
130 surrounded-regions Kotlin solution
2 parents f5804fa + b372b34 commit 216f259

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

kotlin/130-Surrounded-Regions.kt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package kotlin
2+
3+
// Runtime: 356 ms, faster than 72.97% of Kotlin online submissions for Surrounded Regions.
4+
// Memory Usage: 48.5 MB, less than 75.68% of Kotlin online submissions for Surrounded Regions.
5+
// https://leetcode.com/submissions/detail/776042031/
6+
class Solution {
7+
fun solve(board: Array<CharArray>): Unit {
8+
val n = board.size
9+
val m = board[0].size
10+
11+
for (y in 0 until n) {
12+
for (x in 0 until m) {
13+
if (x==0||x==m-1||y==0||y==n-1){
14+
if (board[y][x] == 'O') {
15+
markI(board, y, x)
16+
}
17+
}
18+
}
19+
}
20+
21+
for (y in 0 until n) {
22+
for (x in 0 until m) {
23+
board[y][x] = when(board[y][x]){
24+
'O' -> 'X'
25+
'I' -> 'O'
26+
else -> board[y][x] // could've just 'continue'd only if leetcode uses newer version of Kotlin
27+
}
28+
}
29+
}
30+
}
31+
fun inBound(board: Array<CharArray>, r: Int, c: Int) : Boolean {
32+
val n = board.size
33+
val m = board[0].size
34+
return !(r < 0 || r >= n || c < 0 || c >= m)
35+
}
36+
fun markI(board: Array<CharArray>, y: Int, x: Int) {
37+
if (!inBound(board, y, x)) return
38+
if (board[y][x] != 'O') return
39+
board[y][x] = 'I'
40+
markI(board, y+1, x)
41+
markI(board, y-1, x)
42+
markI(board, y, x+1)
43+
markI(board, y, x-1)
44+
}
45+
}

0 commit comments

Comments
 (0)