Number of Islands
Updated
Problem statement
You are given a map grid with m rows and n columns. Each cell is the character '1' (land) or '0' (water).
Two land cells are connected when they share a side, so one is directly above, below, left or right of the other. Cells that touch only at a corner are not connected. Everything outside the grid is water.
An island is a group of land cells where you can walk from any cell of the group to any other by stepping between connected land cells, and no other land cell is connected to the group. Every land cell is in exactly one island.
Return the number of islands in grid.
Function
numIslands(grid: char[][]) → intExamples
Example 1
grid = [["1","0","1","0","1"],["1","0","1","0","0"],["1","1","1","0","1"],["0","0","0","0","1"]]return = 3Here (r, c) means row r and column c, counting from 0. There are 3 islands. The first is shaped like a U: (0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (1, 2) and (0, 2). Its two arms are joined only through row 2. The second is the single cell (0, 4), because (0, 3) to its left and (1, 4) below it are water. The third is (2, 4) and (3, 4).
Example 2
grid = [["0","1","1","0"],["1","0","0","1"],["0","1","1","0"]]return = 4The land forms a diamond, but the pieces touch only at corners. The top pair (0, 1) and (0, 2) is one island, the bottom pair (2, 1) and (2, 2) is another, and (1, 0) and (1, 3) are one island each. The answer is 4.
Example 3
grid = [["0","0","0"],["0","0","0"]]return = 0There is no land, so there are no islands and the answer is 0.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'.
More Fleetx Onsite Interview questions
Similar questions at other companies
- Number of IslandsIntuit · ONSITE INTERVIEW
- Number of IslandsWhatNot · PHONE SCREEN · ONSITE INTERVIEW
- Number of IslandsExpedia · ONSITE INTERVIEW
- Count Islands in a Binary GridApple · PHONE SCREEN
- Count the IslandsAdobe · PHONE SCREEN
- Number of Islands with Diagonal ConnectivityGoogle · ONSITE INTERVIEW
- Island Count and Maximum AreaOracle · ONSITE INTERVIEW
- Maximum Number of Fish in a GridGlobalization Partners · ONSITE INTERVIEW
- Max Area of IslandGoldman Sachs · ONSITE INTERVIEW
- Max Area of IslandRoku · ONSITE INTERVIEW