0% completed
Solution: Problem Challenge 1
Problem Statement
You are given a 2D matrix containing only 1s (land) and 0s (water).
An island is a connected set of 1s (land) and is surrounded by either an edge or 0s (water). Each cell is considered connected to other cells horizontally or vertically (not diagonally).
There are no lakes on the island, so the water inside the island is not connected to the water around it. A cell is a square with a side length of 1.
The given matrix has only one island, write a function to find the perimeter of that island.
Example 1
Input: matrix =
Output: 14
.....
.....
.....
edisonfreire14
· a year ago
Key intuition:
If there is a island block (a 1 in the matrix) the perimeter of that singular block is 4 - the number of other island blocks it is connected to.
So if you go to every island block and check the 4 directions from it count out of the sides are connected then subtract that from 4 we know the perimeter of that block.
So if you do that for every island block and sum it up it will give you the perimeter for the island in the matrix. This in theory would work to find perimeter of multiple islands, if they had lakes too.
def findIslandPerimeter(self, matrix): # TODO: Write your code here rows = len(matrix) cols = len(matrix[0]) deltas = [(1,0),(-1,0),(0,1),(0,-1)] def check_around(i,j): connected = 0 for i_delta, j_delta in deltas: