forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#1687 from a93a/1905
Create 1905-count-sub-islands.kt
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |