Created
April 18, 2020 01:04
-
-
Save munguial/ce947b9fa6c9211d0a6f16a0f4f56f79 to your computer and use it in GitHub Desktop.
Day 17 - Number of Islands
This file contains hidden or 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
// https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/530/week-3/3302/ | |
class Solution { | |
fun numIslands(grid: Array<CharArray>): Int { | |
var result = 0 | |
for (row in grid.indices) { | |
for (col in grid[0].indices) { | |
if (grid[row][col] == '1') { | |
result += 1 | |
dfs(grid, row, col) | |
} | |
} | |
} | |
return result | |
} | |
fun dfs(grid: Array<CharArray>, row: Int, col: Int) { | |
grid[row][col] = '0' | |
val moves = arrayOf(intArrayOf(0, 1), | |
intArrayOf(1, 0), | |
intArrayOf(-1, 0), | |
intArrayOf(0, -1)) | |
moves.forEach { | |
val newRow = row + it[0] | |
val newCol = col + it[1] | |
if (isValidMove(grid, newRow, newCol)) { | |
dfs(grid, newRow, newCol) | |
} | |
} | |
} | |
fun isValidMove(grid: Array<CharArray>, row: Int, col: Int): Boolean { | |
if (row < 0 || row == grid.size || col < 0 || col == grid[0].size) { | |
return false | |
} | |
if (grid[row][col] == '0') { | |
return false | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment