Ruby - my poor code..


  • 0
    M

    Have fun~

    def island_perimeter(grid)
    	count = 0
        grid.each_with_index do |small_grid, big_index|
        	x_boundary_length = small_grid.size - 1
        	small_grid.each_with_index do |num, small_index|
        		next if num.zero?
        		y_boundary_length = grid.size - 1
    
        		count += 4
        		count -= 1 if big_index != 0 && grid[big_index - 1][small_index] != 0
        		count -= 1 if big_index != y_boundary_length && grid[big_index + 1][small_index] != 0
        		count -= 1 if small_index != 0 && small_grid[small_index - 1] != 0
        		count -= 1 if small_index != x_boundary_length && small_grid[small_index + 1] != 0
        	end
        end
    
        count
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.