Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1687 from a93a/1905
Browse files Browse the repository at this point in the history
Create 1905-count-sub-islands.kt
  • Loading branch information
Ahmad-A0 authored Dec 29, 2022
2 parents 8419a20 + 175dffe commit 75978b9
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions kotlin/1905-count-sub-islands.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution {
fun countSubIslands(grid1: Array<IntArray>, grid2: Array<IntArray>): Int {

fun isValid(i: Int, j: Int) = i in (0 until grid2.size) && j in (0 until grid2[0].size) && grid2[i][j] == 1

val dir = arrayOf(
intArrayOf(1,0),
intArrayOf(-1,0),
intArrayOf(0,1),
intArrayOf(0,-1)
)

fun dfs(i: Int, j: Int): Boolean {
if(grid1[i][j] != 1)
return false
grid2[i][j] = 0
var found = true
for((iD,jD) in dir){
val iN = i + iD
val jN = j + jD
if(isValid(iN, jN))
found = found and dfs(iN, jN)
}
return found
}

var count = 0
for(i in 0 until grid1.size){
for(j in 0 until grid1[0].size){
if(grid1[i][j] == 1 && grid2[i][j] == 1)
if(dfs(i, j) == true)
count++
}
}
return count
}
}

0 comments on commit 75978b9

Please sign in to comment.