Island Perimeter 题解
来源:互联网 发布:java gc日志 编辑:程序博客网 时间:2024/05/16 09:38
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.
链接:点击打开链接
题解:
由题意可知,我们需要求出 “陆地” 的外围长度。首先,我们对矩阵按照从左到右,从上到下的搜索策略进行遍历,当发现该块的值为“1”时,表示陆地,我们记录该块,如果发现有两个相连的“陆地”时,我们同样需要记录。我们用
if(i!=0 && grid[i-1][j]==1) del++;if(j!=0 && grid[i][j-1]==1) del++;
这段代码实现。按照数学上的理论方法,一个块周长为4,如果存在两个块相连接,则会存在边的“抵消”,会使它们拼接的图形周长减少(如:两个周长为4的正方形,连接后周长为4*2-2)。因此,最后“陆地”的外围长度为:(陆地块数量*4) 减去 (重复的陆地块数量*2)。算法复杂度为 O(n²)。
代码:
class Solution {public: int islandPerimeter(vector<vector<int>>& grid) { int ans=0; int del=0; for(int i=0; i<grid.size(); i++){ for(int j=0;j<grid[i].size(); j++){ if(grid[i][j]==1){ ans++; if(i!=0 && grid[i-1][j]==1){ del++; } if(j!=0 && grid[i][j-1]==1){ del++; } } } } return ans*4-del*2; }};
- LeetCode题解:Island Perimeter
- Island Perimeter 题解
- leetcode题解-463. Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- Island Perimeter
- 463. Island Perimeter
- 463. Island Perimeter
- leetcode 463. Island Perimeter
- 数学智力题总结
- mybatis3--7.resultMap高级映射
- 通过screen解决终端模拟器断开连接之后丢失会话的问题
- HDU1281 棋盘游戏 最小点覆盖
- MyBatis学习笔记(4)
- Island Perimeter 题解
- 求最大公约数
- Codeforces Round #401 (Div. 2)【A,B,C,D】
- Find Peak Element
- 从头构建Linux系统之一 —— 前言
- CPU,内存,硬盘,指令之间的关系
- 1.1XAF框架开发视频教程-简单的订单管理实现过程,视频,提纲,及教程源码
- 调用startActivityForResult,onActivityResult无响应的问题
- hdu 5380 Travel with candy (单调队列)@