题目
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:
思路
直接暴力求解,对于每个格子,检查与其相邻的4个格子:
- 如果格子超出边界,则周长+1;否则
- 如果格子是水,则周长+1
这样最终得到的周长就是结果了。
代码
islandPerimeter.go
func getPerimeter(grid [][]int, len1, len2, i, j int) (perimeter int) {
//up
if 0 == i || 0 == grid[i-1][j] {
perimeter++
}
//left
if 0 == j || 0 == grid[i][j-1] {
perimeter++
}
//right
if (len1-1) == i || 0 == grid[i+1][j] {
perimeter++
}
//down
if (len2-1) == j || 0 == grid[i][j+1] {
perimeter++
}
return perimeter
}
func islandPerimeter(grid [][]int) int {
len1 := len(grid)
len2 := len(grid[0])
var perimiter int
for i := 0; i < len1; i++ {
for j := 0; j < len2; j++ {
if 0 == grid[i][j] {
continue
}
per := getPerimeter(grid, len1, len2, i, j)
perimiter += per
}
}
return perimiter
}
测试代码
islandPerimeter_test.go
package _463_Island_Perimeter
import "testing"
func TestIslandPerimeter(t *testing.T) {
input := [][]int{
{0, 1, 0, 0},
{1, 1, 1, 0},
{0, 1, 0, 0},
{1, 1, 0, 0}}
want := 16
ret := IslandPerimeter(input)
if ret == want {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want, ret)
}
}