Number of Islands
Last updated
Last updated
Given a 2D grid consists of "1"s and "0"s, count the number of connected "1"s.
An island ("1"s) can be connected vertically and horizontally. Assume all 4 edges are surrounded by water.
The given input is a char[][]
.
Output: 1
Output: 1+1+1 = 3
This question is essentially searching connected components in a simple graph. We can solve it with either BFS or DFS. We prefer BFS over DFS because 1 1 1 1 1 ... 1
can overflow the call stack. Say we want to eat a hamburger. Do you want to eat normally by taking a couple bites around the side? Or do you want to keep biting in one direction until you reach the end of that direction? Sure both methods can finish the burger, but your mouth might get very full by choosing the second way.
O(mn)
Only destroy the island if the number of 1s is less than k
have a flag at the end of the path, if path_length < k, give permission to destroy the island on the back back (backtracking) otherwise label it as red zone (label is -1 or something so we don't touch it). So we want to measure how long this subway is before we eat it backward. i.e. if it's 12in we don't want to eat it, label it red. But if it's 6in, then eat it backward.
Count number of lakes
Measure the length of the seashore
Segmentfault by Ethan Li