[LeetCode] 463. Island Perimeter 岛的周长
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:

给一个二维的格子图,格子是1表示陆地,0表示水,格子水平或者垂直连接,若干的格子连在一起形成一个小岛,只有一个相连的岛,且岛中没有湖,求岛的周长。
解法1: 遇到为1的格子,检验四个方向是否和陆地相连
解法2: 遇到为1的格子,检查上面和左面是否和陆地相连
Java:
public class Solution {
    public int islandPerimeter(int[][] grid) {
        int islands = 0, neighbours = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 1) {
                    islands++; // count islands
                    if (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighbours
                    if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours
                }
            }
        }
        return islands * 4 - neighbours * 2;
    }
}
Python:
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ans = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
ans += 4
if i > 0 and grid[i-1][j] == 1:
ans -= 2
if j > 0 and grid[i][j-1] == 1:
ans -= 2
return ans
Python:
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0 def sum_adjacent(i, j):
adjacent = (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1),
res = 0
for x, y in adjacent:
if x < 0 or y < 0 or x == len(grid) or y == len(grid[0]) or grid[x][y] == 0:
res += 1
return res count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
count += sum_adjacent(i, j)
return count
Python:
class Solution:
def islandPerimeter(self, grid):
if not grid:
return 0 N = len(grid)
M = len(grid[0])
ans = 0
for i in range(N):
for j in range(M):
for k in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
if i+k[0] < 0 or i + k[0] >= N or j+k[1] < 0 or j+k[1] >= M or grid[i+k[0]][j+k[1]] == 0:
ans += 1
return ans
C++:
class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        if (grid.empty() || grid[0].empty()) return 0;
        int m = grid.size(), n = grid[0].size(), res = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0) continue;
                if (j == 0 || grid[i][j - 1] == 0) ++res;
                if (i == 0 || grid[i - 1][j] == 0) ++res;
                if (j == n - 1 || grid[i][j + 1] == 0) ++res;
                if (i == m - 1 || grid[i + 1][j] == 0) ++res;
            }
        }
        return res;
    }
};
C++:
class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        if (grid.empty() || grid[0].empty()) return 0;
        int res = 0, m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0) continue;
                res += 4;
                if (i > 0 && grid[i - 1][j] == 1) res -= 2;
                if (j > 0 && grid[i][j - 1] == 1) res -= 2;
            }
        }
        return res;
    }
};
Followup: 如果不止一个岛屿
All LeetCode Questions List 题目汇总
[LeetCode] 463. Island Perimeter 岛的周长的更多相关文章
- LeetCode 463. Island Perimeter岛屿的周长 (C++)
		
题目: You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 repr ...
 - LeetCode 463. Island Perimeter (岛的周长)
		
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represen ...
 - LeetCode - 463. Island Perimeter - O(MN)- (C++) - 解题报告
		
原题 原题链接 You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 ...
 - LeetCode 463 Island Perimeter 解题报告
		
题目要求 You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 rep ...
 - LeetCode: 463 Island Perimeter(easy)
		
题目: You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 repr ...
 - 3. leetcode 463 Island Perimeter
		
思路:设原始周长为4*节点数,每当出现一次相邻的情况,原始周长会减2.
 - 463 Island Perimeter 岛屿的周长
		
详见:https://leetcode.com/problems/island-perimeter/description/ C++: class Solution { public: int isl ...
 - 463. Island Perimeter - LeetCode
		
Question 463. Island Perimeter Solution 题目大意:给出一个二维数组1表示陆地0表示海,求陆地的周长 思路: 重新构造一张地图grid2即一个二维数组,比原数组大 ...
 - 【LeetCode】Island Perimeter 解题报告
		
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
 
随机推荐
- 项目Alpha冲刺--10/10
			
项目Alpha冲刺--10/10 作业要求 这个作业属于哪个课程 软件工程1916-W(福州大学) 这个作业要求在哪里 项目Alpha冲刺 团队名称 基于云的胜利冲锋队 项目名称 云评:高校学生成绩综 ...
 - 项目Alpha冲刺 8
			
作业描述 课程: 软件工程1916|W(福州大学) 作业要求: 项目Alpha冲刺(团队) 团队名称: 火鸡堂 作业目标: 介绍第8天冲刺的项目进展.问题困难和心得体会 1.团队信息 队名:火鸡堂 队 ...
 - Docker创建mysql镜像
			
原文: https://blog.csdn.net/uk8692/article/details/49386679 https://blog.csdn.net/qq362228416/article/ ...
 - 我的ImageIO.write ByteArrayOutputStream为什么这么慢?
			
File.createTempFile(prefix, suffix),创建一个临时文件,再使用完之后清理即可.但是遇到如下两个坑: String prefix = "temp"; ...
 - The database returned no natively generated identity value错误解决方案
			
原因:hibernate项目中在学生表的配置文件中: <id name="studentno" column="studentno"> <ge ...
 - rac集群状态脚本执行awk拼接有问题
			
再shell中拿出来拼接没问题,在脚本中运行就有问题,
 - Linux 系统管理——账号管理
			
一.用户账号管理 1.用户账户概述 用户账户的常见分类: 超级用户:root uid=0 gid=0 权限最大 普通用户:uid>=500 做一般权限的系统管理,权限有限. 程序用户:1 ...
 - vuex 之既生‘mutation’何生‘action’
			
vuex 中,action 及 mutation 均为操作数据的作用而存在,既然二者均可改变数据,为什么要分成两个方法来处理呢,因为: Mutation 必须是同步函数 mutations: { so ...
 - rust学习(二)
			
play on line match if #![allow(unused)] fn write_bar(size: u64){ match size{ o => println!(" ...
 - app内嵌H5的上传图片的功能
			
1.上传组件 <!-- - hasBorder {Boolean} cell底部边框,oneline 为 true 有效 - inlineBorder {Boolean} cell底部短边框 - ...