My Ruby Solution


  • 0
    T

    Time Complexity - O(m*n)
    Space Complexity - O(1)

    • m = num of rows
    • n = num of cols
    def island_perimeter(grid)
      land, neighbors = 0, 0
    
      num_rows = grid.length
      num_cols = grid.first.length
    
      (0...num_rows).each do |row_idx|
        (0...num_cols).each do |col_idx|
          if grid[row_idx][col_idx] == 1
            land += 1
    
            if row_idx + 1 < num_rows && grid[row_idx + 1][col_idx] == 1
              neighbors += 1
            end
    
            if col_idx + 1 < num_cols && grid[row_idx][col_idx + 1] == 1
              neighbors += 1
            end
          end
        end
      end
    
      (land * 4) - (neighbors * 2)
    end
    

Log in to reply
 

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