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
题目大意:给定一个矩阵,1代表小岛,0代表水,求出小岛的周长
思路:小岛的周长等于小岛的个数4-2小岛邻居的个数
代码
package HashTable; /** * @author OovEver * 2018/1/11 13:30 */ public class LeetCode463 { public int islandPerimeter(int[][] grid) { int island = 0, neighbors = 0; for(int i=0;i<grid.length;i++) { for(int j=0;j<grid[0].length;j++) { if (grid[i][j] == 1) { island++; if (i < grid.length - 1) { if (grid[i + 1][j] == 1) { neighbors++; } } if (j < grid[i].length - 1) { if (grid[i][j + 1] == 1) { neighbors++; } } } } } return 4 * island - 2 * neighbors; } }