diff --git a/leetcode/0463-island-perimeter/README.md b/leetcode/0463-island-perimeter/README.md new file mode 100644 index 0000000..605241b --- /dev/null +++ b/leetcode/0463-island-perimeter/README.md @@ -0,0 +1,39 @@ +

You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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", meaning the water inside 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 1:

+ +
+Input: grid = [[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 above.
+
+ +

Example 2:

+ +
+Input: grid = [[1]]
+Output: 4
+
+ +

Example 3:

+ +
+Input: grid = [[1,0]]
+Output: 4
+
+ +

 

+

Constraints:

+ + diff --git a/leetcode/0463-island-perimeter/solution.go b/leetcode/0463-island-perimeter/solution.go new file mode 100644 index 0000000..aa106ab --- /dev/null +++ b/leetcode/0463-island-perimeter/solution.go @@ -0,0 +1,42 @@ +func islandPerimeter(grid [][]int) int { + n := len(grid) + m := len(grid[0]) + x := 0 + y := 0 + vis := make([][]bool, n) + for i := range grid { + vis[i] = make([]bool, m) + for j := range grid[i] { + vis[i][j] = false + } + } + for i := range grid { + for j := range grid[i] { + if grid[i][j] == 1 { + x = i + y = j + break + } + } + if grid[x][y] == 1 { + break; + } + } + ret := 0 + q := []int {x,y} + for len(q) != 0 { + x := q[0] + y := q[1] + q = q[2:] + if x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0 { + ret++ + continue + } + if vis[x][y] { + continue + } + vis[x][y] = true + q = append(q, x+1, y, x-1, y, x, y+1, x, y-1) + } + return ret +}