scala version


  • 0
    M
      def islandPerimeter(grid: Array[Array[Int]]): Int = {
        var islands = 0
        var neighbors = 0
        for (i <- grid.indices) {
          for (j <- grid(0).indices) {
            if (grid(i)(j) == 1) {
              islands += 1
              if (j < grid.length - 1 && grid(i)(j + 1) == 1) neighbors += 1
              if (i < grid(0).length - 1 && grid(i + 1)(j) == 1) neighbors += 1
            }
          }
        }
        islands * 4 - neighbors * 2
      }
    

  • 0
    L

    HI, bro.When i used your code running online, i got this message “Compile time limit exceeded“. Have you seen? thx

    object Solution {
       def islandPerimeter(grid: Array[Array[Int]]): Int = {
        var islands = 0
        var neighbors = 0
        for (i <- grid.indices) {
          for (j <- grid(0).indices) {
            if (grid(i)(j) == 1) {
              islands += 1
              if (j < grid.length - 1 && grid(i)(j + 1) == 1) neighbors += 1
              if (i < grid(0).length - 1 && grid(i + 1)(j) == 1) neighbors += 1
            }
          }
        }
        islands * 4 - neighbors * 2
      }
    }
    

Log in to reply
 

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