Created
December 22, 2022 08:32
-
-
Save Veeyikpong/69424c8212385bc0551d53122130dd1b to your computer and use it in GitHub Desktop.
Count number of islands
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
numIslands( | |
grid = arrayOf( | |
charArrayOf('1', '1', '1', '1', '0'), | |
charArrayOf('1', '1', '0', '1', '0'), | |
charArrayOf('1', '1', '0', '0', '0'), | |
charArrayOf('0', '0', '0', '0', '0') | |
) | |
) | |
numIslands( | |
grid = arrayOf( | |
charArrayOf('1', '1', '0', '0', '0'), | |
charArrayOf('1', '1', '0', '0', '0'), | |
charArrayOf('0', '0', '1', '0', '0'), | |
charArrayOf('0', '0', '0', '1', '1') | |
) | |
) | |
fun numIslands(grid: Array<CharArray>): Int { | |
var islandCount = 0 | |
grid.forEachIndexed { rowIndex, chars -> | |
chars.forEachIndexed { colIndex, c -> | |
// If we found a land, we all adjacent to zero (water) and increase island count by 1 | |
if (c == '1') { | |
islandCount += setAdjacentToZero(rowIndex, colIndex, grid) | |
} | |
} | |
} | |
return islandCount | |
} | |
fun setAdjacentToZero(rowIndex: Int, colIndex: Int, grid: Array<CharArray>): Int { | |
if (rowIndex < 0 || colIndex < 0 || rowIndex >= grid.size || colIndex >= grid[rowIndex].size || grid[rowIndex][colIndex] == '0') | |
return 0 | |
grid[rowIndex][colIndex] = '0' | |
setAdjacentToZero(rowIndex + 1, colIndex, grid) | |
setAdjacentToZero(rowIndex - 1, colIndex, grid) | |
setAdjacentToZero(rowIndex, colIndex + 1, grid) | |
setAdjacentToZero(rowIndex, colIndex - 1, grid) | |
return 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment