Island-Perimeter

This is definitely an easy one because all you have to do is to that if a block is filled up, check the four conditions:

  1. If the block is at the top row or if the block whose top is not filled up, then increase sides variable
  2. If the block is at the bottom row or if the block whose bottom is not filled up then increase sides variable
  3. If the block is the left most column or if the block whose left side is not filled up then increase sides variable
  4. Finally, if the block is the right most column of if the block whose right side is not filled up then increase sides variable.
class Solution {
    fun islandPerimeter(grid: Array<IntArray>): Int {
        var sides = 0
        for(index in 0 until grid.size){
            for(subIndex in 0 until grid.first().size){
                if(grid[index][subIndex] == 1){                    
                    if(index == 0 || grid[index-1][subIndex] == 0) sides++     // top
                    if(index == grid.size - 1 || grid[index+1][subIndex] == 0) sides++ // bottom   
                    if(subIndex == 0 || grid[index][subIndex-1] == 0) sides++ // left
                    if(subIndex == grid.first().size - 1 || grid[index][subIndex+1] == 0) sides++ // right           
                }
            }
        }
        
        return sides
    }
}
Runtime: 388 ms, faster than 54.55% of Kotlin online submissions for Island Perimeter.
Memory Usage: 58.3 MB, less than 100.00% of Kotlin online submissions for Island Perimeter.