LeetCode-934
Question:
You are given an n x n
binary matrix grid
where 1
represents land and 0
represents water.
An island is a 4-directionally connected group of 1
‘s not connected to any other 1
‘s. There are exactly two islands in grid
.
You may change 0
‘s to 1
‘s to connect the two islands to form one island.
Return the smallest number of 0
‘s you must flip to connect the two islands.
Solution:
Since there are only 2 islands in the stem, we can use a deep search to find one of them first.
Using breadth-first search for this island can be interpreted as expanding this island outward 1 at a time, and when the expansion finds the other island for the Nth time, it is the solution sought by the stem.
###
Code:
1 | class Solution { |