463. Island Perimeter
来源:互联网 发布:php从入门到精通视频 编辑:程序博客网 时间:2024/05/18 13:06
题目
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:
我的解法(比答案好)
public class Solution { public int islandPerimeter(int[][] grid) { int prm = 0; int rowNum = grid.length; int colNum = grid[0].length; // 遍历数组。若元素是小岛,则判断其四周邻接是否有小岛,每个小岛对周长的贡献等于4-邻接小岛数 for(int i = 0; i < rowNum; i ++) for(int j = 0; j < colNum; j ++){ int island = grid[i][j]; if(island == 1){ // 三目运算符简化if else int above = (i - 1 >= 0) ? ((grid[i - 1][j] == 1) ? 1 : 0) : 0; int below = (i + 1 < rowNum) ? ((grid[i + 1][j] == 1) ? 1 : 0) : 0; int left = (j - 1 >= 0) ? ((grid[i][j -1 ] == 1) ? 1 : 0) : 0; int right = (j + 1 < colNum) ? ((grid[i][j + 1] == 1) ? 1 : 0): 0; prm += island * 4 - above - below - left - right; } } return prm; } }
0 0
- 463. Island Perimeter
- 463. Island Perimeter
- leetcode 463. Island Perimeter
- leetcode 463. Island Perimeter
- 463. Island Perimeter
- 463. Island Perimeter
- LeetCode 463. Island Perimeter
- 463. Island Perimeter
- Tutorial: 463. Island Perimeter
- 463. Island Perimeter
- 【LeetCode】 463. Island Perimeter
- [leetcode]463. Island Perimeter
- Leetcode-463. Island Perimeter
- 463. Island Perimeter
- Leetcode 463. Island Perimeter
- 463. Island Perimeter
- 463. Island Perimeter*
- 【Leetcode】463. Island Perimeter
- 查看html特殊字符编码
- Ubuntu14.04LTS下应用Caffe训练Cifar10错误案例分析与解决方案1
- 蒙特卡罗算法和拉斯维加斯算法
- ubuntu16.3 python pip 安装,使用
- Intellij Idea 中hibernate 反向生成实体
- 463. Island Perimeter
- 基于TP框架写的ajax无刷新分页
- 自定义View基础 - 最易懂的自定义View原理系列(1)
- python读书笔记-电子邮件
- 组建创业技术团队
- 华为机试在线训练-牛客网(31)配置文件恢复
- Excel-日常用到的
- LeetCode 9. Palindrome Number
- 【tool】ADDM和STA