zoukankan      html  css  js  c++  java
  • 0463. Island Perimeter (E)

    Island Perimeter (E)

    题目

    You are given a map in form of a two-dimensional integer grid where 1 represents land and 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" (water inside that 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.

    Example:

    Input:
    [[0,1,0,0],
     [1,1,1,0],
     [0,1,0,0],
     [1,1,0,0]]
    
    Output: 16
    

    Explanation: The perimeter is the 16 yellow stripes in the image below:


    题意

    给定一个矩阵图表示的海域,其中有一个连通的小岛,求该小岛的周长。

    思路

    直接遍历一遍矩阵,对于每一个小岛,判断与它相连的小岛数为n,那么当前小岛贡献的周长就是4-n。

    注意到对于小岛这个整体,只要左边有一条边,那么在相同水平位置的右边也有一条边;只要上边有一条边,那么在相同垂直位置的下边也有一条边,所以也可以只统计每个方块左边和上边的贡献,最后乘2即可。


    代码实现

    Java

    统计四边

    class Solution {
        public int islandPerimeter(int[][] grid) {
            int perimeter = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 1) {
                        perimeter += edges(grid, i, j);
                    }
                }
            }
            return perimeter;
        }
    
        private int edges(int[][] grid, int i, int j) {
            int[] diffI = { -1, 0, 1, 0 };
            int[] diffJ = { 0, 1, 0, -1 };
            int count = 4;
            for (int x = 0; x < 4; x++) {
                int nextI = i + diffI[x];
                int nextJ = j + diffJ[x];
                if (nextI >= 0 && nextI < grid.length && nextJ >= 0 && nextJ < grid[0].length && grid[nextI][nextJ] == 1) {
                    count--;
                }
            }
            return count;
        }
    }
    

    统计两边

    class Solution {
        public int islandPerimeter(int[][] grid) {
            int count = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 1 && (i == 0 || grid[i - 1][j] == 0)) count++;
                    if (grid[i][j] == 1 && (j == 0 || grid[i][j - 1] == 0)) count++;
                }
            }
            return count * 2;
        }
    }
    
  • 相关阅读:
    C# 创建Excel并写入内容
    c#中使用excel
    C#中EXCEL表格的内容进度条实现
    WinForm c#操作Excel
    如何使用 Visual C# .NET 处理 Excel 事件
    C#与Excel的交互示例
    c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll读取Excel文件
    C#在excel中添加超链接
    ASP.NET学习笔记(3)
    ASP.NET学习笔记(4)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13264603.html
Copyright © 2011-2022 走看看