# Leetcode - Island Perimeter

violet posted @ Jul 08, 2020 01:12:47 AM in 算法 with tags Algorithm Golang DFS , 364 阅读

https://leetcode.com/problems/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:

```Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:

```
```func islandPerimeter(grid [][]int) int {
count := 0
found := false
m := len(grid)
n := len(grid[0])
for i := 0; i < m; i++ {
if found {
break
}
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
walk(grid, &count, i, j)
found = true
break
}
}
}
for i := 0; i < m; i++ {
if grid[i][0] == 2 {
count++
}
if grid[i][n-1] == 2 {
count++
}
}
for j := 0; j < n; j++ {
if grid[0][j] == 2 {
count++
}
if grid[m-1][j] == 2 {
count++
}
}

return count
}

func walk(grid [][]int, count *int, i, j int) {
if i < 0 || i >= len(grid) || j < 0 || j >= len(grid[0]) || grid[i][j] == 2 {
return
}
if grid[i][j] == 0 {
(*count)++
return
}
grid[i][j] = 2
dirs := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
for _, d := range dirs {
x := d[0] + i
y := d[1] + j
walk(grid, count, x, y)
}
}```
Noida Escorts 说:
Dec 21, 2021 01:44:10 PM
This is a great article and a great read for me. Okhla Escorts Paharganj Escorts Prashant Vihar Escorts Punjabi Bagh Escorts It's my first visit to your blog

AP 10th Gk Model Pap 说:
Sep 11, 2022 06:41:51 PM

General Knowlorge is most important subject to all Class 10 students studying in English Medium, AP 10th Gk Model Paper Telugu Medium & Urdu Medium of the State Board. So every student who is studying in the state Government & Private Schools can download the AP 10th GK Model Paper 2023 Pdf with answer solutions designed and suggested by subject experts. General Knowlorge is most important subject to all Class 10 students studying in English Medium.

(输入验证码)
or Ctrl+Enter