问题:
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: 16Explanation: The perimeter is the 16 yellow stripes in the image below:
解决:
①扫描数组,值为1时周长加4,然后看上下左右的值是否为1,若是,则减去相邻的边。耗时162ms。
public class Solution {
public int islandPerimeter(int[][] grid) { int len1 = grid.length; int perimeter = 0; for (int i = 0;i < len1 ;i ++ ) { int len2 = grid[i].length; for (int j = 0;j < len2 ;j ++ ) { if (grid[i][j] == 1) { perimeter += 4; if(j + 1 < len2 && grid[i][j + 1] == 1){//左 perimeter -= 1; } if (j - 1 >= 0 && grid[i][j - 1] == 1) {//右 perimeter -= 1; } if (i + 1 < len1 && grid[i + 1][j] == 1) {//下 perimeter -= 1; } if (i - 1 >= 0 && grid[i - 1][j] == 1) {//上 perimeter -= 1; } } } } return perimeter; } }②思路大体上与上面一致,但是按照下面的方法来写更简单。耗时118ms。
public class Solution {
public int islandPerimeter(int[][] grid) { int len1 = grid.length; int len2 = grid[0].length; int perimeter = 0; for (int i = 0;i < len1 ;i ++ ) { for (int j = 0;j < len2 ;j ++ ) { if (grid[i][j] == 0) { continue; } if (i - 1 < 0 || i - 1 >= 0 && grid[i - 1][j] == 0) {//上边 perimeter ++; } if (j - 1 < 0 || j - 1 >= 0 && grid[i][j - 1] == 0) {//左边 perimeter ++; } if (i + 1 == len1 || i + 1 < len1 && grid[i + 1][j] == 0) { perimeter ++; } if (j + 1 == len2 || j + 1 < len2 && grid[i][j + 1] == 0) { perimeter ++; } } } return perimeter; } }③不知道要怎么用hash表,之后再改吧