84. The algorithm is simple and swift island perimeter

Given a two-dimensional grid map 0 and 1, where 1 represents 0 for land waters.

Lattice grid horizontal and the vertical direction are connected (not connected in the diagonal direction). The entire grid is completely surrounded by water, but exactly an island (or, one or more land grid connected islands composition represented).

No islands "lake" ( "Lake" refers to the island is connected to the water inside the water around the island and does not). Lattice is a square of 1. The grid is rectangular, and the width and height of not more than 100. Calculate 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

Explain: it is following the circumference 16 of the yellow image side:

solution:
 

    func islandPerimeter(_ grid: [[Int]]) -> Int {
       let  length = grid.count
       let width = grid[0].count
       var prm = 0
        for i in 0..<length{
            for j in 0..<width{
                if grid[i][j] == 1{
                    if j == 0 || grid[i][j - 1] == 0{  //判断上方
                        prm += 1
                    }
                    if i == 0 || grid[i - 1][j] == 0{   //判断左边
                        prm += 1
                    }
                }
            }
        }
        return prm * 2

    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93459984