463. 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 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 elseint 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;}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
