zoukankan      html  css  js  c++  java
  • 463. Island Perimeter

    package LeetCode_463
    
    /**
     * 463. Island Perimeter
     * https://leetcode.com/problems/island-perimeter/description/
     *
     * You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
    Grid cells are connected horizontally/vertically (not diagonally).
    The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
    The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island.
    One cell is a square with side length 1.
    The grid is rectangular, width and height don't exceed 100.
    Determine the perimeter of the island.
     * */
    class Solution {
        /*
        * solution: two loops, calculate total perimeter than minus total neighbours,
        * Time complexity:O(n), Space complexity:O(1)
        * */
        fun islandPerimeter(grid: Array<IntArray>): Int {
            if (grid.isEmpty()) {
                return 0
            }
            var area = 0
            var connect = 0
            val m = grid.size
            val n = grid[0].size
            for (i in 0 until m) {
                for (j in 0 until n) {
                    if (grid[i][j] == 0) {
                        continue
                    }
                    area++
                    //check 4 directions if a neighbours
                    if (i > 0 && grid[i - 1][j] == 1) {
                        connect++
                    }
                    if (i < m - 1 && grid[i + 1][j] == 1) {
                        connect++
                    }
                    if (j > 0 && grid[i][j - 1] == 1) {
                        connect++
                    }
                    if (j < n - 1 && grid[i][j + 1] == 1) {
                        connect++
                    }
                }
            }
            return area * 4 - connect
        }
    }
  • 相关阅读:
    Mysql(11)_Mysql权限与安全
    Mysql(10)_存储过程与流程控制
    Java(43)_AWT事件处理挂关闭生效
    6.实现合同测试用例
    6.测试库优化
    5.案例回顾及编写测试用例
    4.测试案例实现代码库与测试用例V2.0
    3.测试案例实现代码库与测试用例
    markdown语法学习
    1.faker批量随机造数据
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13659364.html
Copyright © 2011-2022 走看看