Skip to content

Commit 42177c3

Browse files
committed
- Add: Max Area of Island
1 parent 6942420 commit 42177c3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
fun maxAreaOfIsland(g: Array<IntArray>): Int {
3+
val rows = g.size
4+
val cols = g[0].size
5+
val dirs = intArrayOf(-1,0,1,0,-1)
6+
7+
var res = 0
8+
val visit = HashSet<Pair<Int,Int>>()
9+
val q = LinkedList<Pair<Int,Int>>()
10+
fun count(): Int {
11+
var res = 0
12+
while (q.isNotEmpty()) {
13+
res++
14+
val coord = q.poll()
15+
for (d in 0 until 4) {
16+
val nr = coord.first + dirs[d]
17+
val nc = coord.second + dirs[d+1]
18+
val newCoord = nr to nc
19+
if (nr in 0 until rows &&
20+
nc in 0 until cols &&
21+
newCoord !in visit &&
22+
g[nr][nc] == 1) {
23+
q.add(newCoord)
24+
visit.add(newCoord)
25+
}
26+
}
27+
}
28+
return res
29+
}
30+
31+
repeat(rows) { r ->
32+
repeat(cols) { c ->
33+
val coord = r to c
34+
if (coord !in visit &&
35+
g[r][c] == 1) {
36+
q.add(coord)
37+
visit.add(coord)
38+
res = maxOf(res, count())
39+
}
40+
}
41+
}
42+
return res
43+
}
44+
}

0 commit comments

Comments
 (0)