Count Disappearing Connected Tiles
Problem statement
A player selects the tile at [row,col] in a rectangular integer grid. The selected tile disappears, along with every tile with the same value connected to it directly or transitively through immediately adjacent cells above, below, left or right. Tiles are not connected diagonally.
Return how many tiles disappear, including the selected tile. Other components with the same number are not counted; tiles with different values stop connectivity.
For this exercise, assume a nonempty equal-width board with 1 to 30 rows and columns, integer digits 0 through 9, and a valid zero-based selection.
Function
disappear(grid: int[][], row: int, col: int) → intExamples
Example 1
grid = [[4,4,4,4],[5,5,5,4],[2,5,7,5]]row = 0col = 0return = 5This exact source testcase removes 5 equal-valued tiles from the selected four-neighbor component.
Example 2
grid = [[4,4,4,4],[5,5,5,4],[2,5,7,5]]row = 1col = 1return = 4This exact source testcase removes 4 equal-valued tiles from the selected four-neighbor component.
Example 3
grid = [[4,4,4,4],[5,5,5,4],[2,5,7,5]]row = 1col = 0return = 4This exact source testcase removes 4 equal-valued tiles from the selected four-neighbor component.
Example 4
grid = [[0,3,3,3,3,3,3],[0,1,1,1,1,1,3],[0,2,2,0,2,1,4],[0,1,2,2,2,1,3],[0,1,1,1,1,1,3],[0,0,0,0,0,0,0]]row = 0col = 0return = 12This exact source testcase removes 12 equal-valued tiles from the selected four-neighbor component.
Example 5
grid = [[0,3,3,3,3,3,3],[0,1,1,1,1,1,3],[0,2,2,0,2,1,4],[0,1,2,2,2,1,3],[0,1,1,1,1,1,3],[0,0,0,0,0,0,0]]row = 3col = 0return = 12This exact source testcase removes 12 equal-valued tiles from the selected four-neighbor component.
Example 6
grid = [[0,3,3,3,3,3,3],[0,1,1,1,1,1,3],[0,2,2,0,2,1,4],[0,1,2,2,2,1,3],[0,1,1,1,1,1,3],[0,0,0,0,0,0,0]]row = 1col = 1return = 13This exact source testcase removes 13 equal-valued tiles from the selected four-neighbor component.
Example 7
grid = [[0,3,3,3,3,3,3],[0,1,1,1,1,1,3],[0,2,2,0,2,1,4],[0,1,2,2,2,1,3],[0,1,1,1,1,1,3],[0,0,0,0,0,0,0]]row = 2col = 2return = 6This exact source testcase removes 6 equal-valued tiles from the selected four-neighbor component.
Example 8
grid = [[0,3,3,3,3,3,3],[0,1,1,1,1,1,3],[0,2,2,0,2,1,4],[0,1,2,2,2,1,3],[0,1,1,1,1,1,3],[0,0,0,0,0,0,0]]row = 0col = 3return = 7This exact source testcase removes 7 equal-valued tiles from the selected four-neighbor component.
Example 9
grid = [[0]]row = 0col = 0return = 1This exact source testcase removes 1 equal-valued tiles from the selected four-neighbor component.
Example 10
grid = [[1,1,1],[1,1,1],[1,1,1]]row = 0col = 0return = 9This exact source testcase removes 9 equal-valued tiles from the selected four-neighbor component.
Constraints
- For this exercise, assume
1 <= grid.length, grid[0].length <=30and every row has the same length. 0 <= grid[r][c] <=9.0 <= row < grid.lengthand0 <= col < grid[0].length.