首页 > 考试 > 其他 > 正文
LeetCode 463. Island Perimeter
2016-11-23       个评论    来源:James Pan  
收藏    我要投稿

原题网址:https://leetcode.com/problems/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:
\

方法:逐个扫描。

 

public class Solution {
    public int islandPerimeter(int[][] grid) {
        int p = 0;
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 0) continue;
                if (i == 0 || grid[i - 1][j] == 0) p++;
                if (i == grid.length - 1 || grid[i + 1][j] == 0) p++;
                if (j == 0 || grid[i][j - 1] == 0) p++;
                if (j == grid[i].length - 1 || grid[i][j + 1] == 0) p++;
            }
        }
        return p;
    }
}


 

点击复制链接 与好友分享!回本站首页
相关TAG标签 LeetCode
上一篇:2016 acm/icpc 青岛网络赛 题解(hdu 5878-5889)
下一篇:[leetcode] 454. 4Sum II 解题报告
相关文章
图文推荐
文章
推荐
热门新闻

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训
版权所有: 红黑联盟--致力于做实用的IT技术学习网站