博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Island Perimeter
阅读量:6148 次
发布时间:2019-06-21

本文共 1398 字,大约阅读时间需要 4 分钟。

Problem

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:

[[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]]

Answer: 16

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

island.png

Solution

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) {                    count += 4;                    count -= findOnesAround(grid, i, j);                }            }        }        return count;    }    private int findOnesAround(int[][] grid, int i, int j) {        int count = 0;        if (i+1 < grid.length && grid[i+1][j] == 1) count++;        if (i-1 >= 0 && grid[i-1][j] == 1) count++;        if (j+1 < grid[0].length && grid[i][j+1] == 1) count++;        if (j-1 >= 0 && grid[i][j-1] == 1) count++;        return count;    }}

转载地址:http://pgmya.baihongyu.com/

你可能感兴趣的文章
SpringMVC权限管理
查看>>
spring 整合 redis 配置
查看>>
redhat6.1下chrome的安装
查看>>
cacti分组发飞信模块开发
查看>>
浅析LUA中游戏脚本语言之魔兽世界
查看>>
飞翔的秘密
查看>>
Red Hat 安装源包出错 Package xxx.rpm is not signed
查看>>
编译安装mysql-5.6.16.tar.gz
查看>>
类与成员变量,成员方法的测试
查看>>
活在当下
查看>>
每天进步一点----- MediaPlayer
查看>>
PowerDesigner中CDM和PDM如何定义外键关系
查看>>
跨域-学习笔记
查看>>
the assignment of reading paper
查看>>
android apk 逆向中常用工具一览
查看>>
MyEclipse 报错 Errors running builder 'JavaScript Validator' on project......
查看>>
Skip List——跳表,一个高效的索引技术
查看>>
Yii2单元测试初探
查看>>
五、字典
查看>>
前端js之JavaScript
查看>>