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
原创粉丝点击