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:
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; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/77097.html
摘要:要求计算出岛屿的周长。思路和代码这题不难,直观的来看,其实只要判断出这一块土地几面临海就知道需要加上几条边长。临海的判断有两个,一个是这块地位于数组的边缘,一个是这块地相邻的元素为,即海洋。代码如下上方临海左侧临海右侧临海下方临海 题目要求 You are given a map in form of a two-dimensional integer grid where 1 rep...
摘要:题目链接题目分析给定一个二维数组,代表一个二维表格。代表有内容,代表没有。思路最简单的办法是,判断当前格子是否位,且上下左右是否为。当都为时,即当前位置是单独的一个格子,算上下左右共条边。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 463. Island Perimeter 题目链接 463. Island Perimeter 题目分析 给定一个二维数组,代表一个二维表格。 里...
摘要:思路对给定的数组进行降序排序,使最大的数字在前面。取最大的前三条,判断任两边之和是否大于第三边。是则返回周长即可。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D62 976. Largest Perimeter Triangle 题目链接 976. Largest Perimeter Triangle 题目分析 给定数字数组,任取三条边形成三角形,返回最大边长。 思路 对给定的数...
Problem Given a non-empty 2D array grid of 0s and 1s, an island is a group of 1s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are s...
摘要:返回注意答案并不是因为陆地相连要求必须是在上下左右四个方向。返回应为想法我们还是要遍历数组中的每一个元素。如果数组元素值为,则我们以这个值为起点进行深度优先搜索。 题目详情 Given a non-empty 2D array grid of 0s and 1s, an island is a group of 1s (representing land) connected 4-di...
阅读 2376·2021-09-22 15:15
阅读 640·2021-09-02 15:11
阅读 1784·2021-08-30 09:48
阅读 1884·2019-08-30 15:56
阅读 1480·2019-08-30 15:52
阅读 2042·2019-08-30 15:44
阅读 431·2019-08-29 16:29
阅读 1538·2019-08-29 11:06