Best Island Total with Row-Major Boundary Cells
Trees & GraphsAuto-graded · 21 test casesLast updated
Find connected components in a signed grid and pick the best-scoring one, with and without a no-negatives rule, reporting its first and last row-major cells.
Best Island Report
A grid of integers describes a map. A cell with value 0 is water, and any other value (positive or negative) is land. Two land cells are neighbors if they share a side (up, down, left, right); diagonals do not count. An island is a maximal group of land cells connected through neighbors. The total of an island is the sum of its cell values, and totals can be negative.
Cells are ordered in row-major order: (r1, c1) comes before (r2, c2) if r1 < r2, or if r1 == r2 and c1 < c2.
For each island, define:
- its first cell: the earliest of its cells in row-major order,
- its last cell: the latest of its cells in row-major order.
Selection rule
From a set of candidate islands, choose the one with the largest total. If several share the largest total, choose the one whose last cell is latest in row-major order. Distinct islands never share a cell, so exactly one island is chosen.
Task
Write a function that makes the selection twice:
"all": candidates are all islands."nonnegative": candidates are only islands in which every cell value is>= 0(since0is water, this means every cell is positive). An island with even one negative cell is excluded entirely; you cannot drop the negative cell and keep the rest.
For each selection, report the chosen island's total, its first cell, and its last cell.
Output format
Return a dictionary with two keys, "all" and "nonnegative". Each maps to a dictionary with keys:
"sum": the island's total (integer),"index": the island's first cell as[r, c](0-based),"last_index": the island's last cell as[r, c](0-based).
If a selection has no candidate island (the grid is empty, has no land, or, for "nonnegative", every island contains a negative cell), then all three values for that selection are None.
Constraints
- The grid has
mrows andncolumns, wheremandncan each be0(an empty grid is possible). - All rows have the same length.
- Each cell is an integer;
0is water and any other value is land. - A grid can be large enough that deep recursion is risky, so prefer an iterative traversal.
- Do not rely on the input being a particular shape beyond the above.
Examples
Example 1
Input: largest_island_report([[1, 2, 0], [-4, 3, 0], [0, 0, 5]])
Output: {'all': {'sum': 5, 'index': [2, 2], 'last_index': [2, 2]}, 'nonnegative': {'sum': 5, 'index': [2, 2], 'last_index': [2, 2]}}
Example 2
Input: largest_island_report([[1, 0, 2], [0, -3, 0], [4, 0, 5]])
Output: {'all': {'sum': 5, 'index': [2, 2], 'last_index': [2, 2]}, 'nonnegative': {'sum': 5, 'index': [2, 2], 'last_index': [2, 2]}}
Example 3
Input: largest_island_report([[0, 0], [0, 0]])
Output: {'all': {'sum': None, 'index': None, 'last_index': None}, 'nonnegative': {'sum': None, 'index': None, 'last_index': None}}
Hints
Hint 1
Treat each island as a connected component: scan the grid, and whenever you meet unvisited land, explore the whole island with a stack or queue so each cell is processed once.
Hint 2
While exploring an island, track four things: the running sum, whether any cell is negative, and the minimum and maximum (row, column) pairs seen. Python tuple comparison matches row-major order.
Hint 3
Keep two running bests, one over all islands and one over only islands without negative cells. Compare by total first, then by last cell. Return None fields when a best never gets set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every part of the task has the same shape: find each island once, compute a small summary of it, then choose among the summaries.
- Scan the grid in row-major order. When you meet a land cell that has not been visited, start an iterative depth-first traversal (explicit stack) from it, marking cells as visited when they are pushed.
- During the traversal, accumulate for that island:
total: the sum of cell values,nonneg: whether every cell is>= 0,first: the minimum(r, c)over its cells,last: the maximum(r, c)over its cells.
- Compare the island to two running bests using the key
(total, last). Python compares tuples lexicographically, so this prefers the larger total and breaks ties by the later last cell. The island is always compared against the "all" best, and also against the "nonnegative" best ifnonnegis true. - Format the results. A best that was never set becomes
Noneforsum,indexandlast_index.
Why it is correct
- The traversal starts only from unvisited land and visits every land cell reachable through side neighbors, so each island is found exactly once.
- Each cell of an island is processed exactly once, so
total,nonneg,firstandlastare exact. - The first cell found by the outer scan happens to be the island's first cell, but tracking min and max over all visited cells is the safe way, and it is required for the last cell.
- Because islands are disjoint, their last cells differ, so the key
(total, last)has no ties and picks a unique island. - Excluding an island with any negative cell from the second selection matches the rule that you cannot drop part of an island.
Complexity
- Time: O(m * n). Each cell is visited a constant number of times and checks four neighbors.
- Space: O(m * n) for the visited matrix and, in the worst case, the stack.
Reference solution
from typing import Dict, List
def largest_island_report(grid: List[List[int]]) -> Dict[str, Dict[str, object]]:
rows = len(grid)
cols = len(grid[0]) if rows else 0
seen = [[False] * cols for _ in range(rows)]
best_all = None
best_nonneg = None
for r in range(rows):
for c in range(cols):
if grid[r][c] == 0 or seen[r][c]:
continue
stack = [(r, c)]
seen[r][c] = True
total = 0
nonneg = True
first = (r, c)
last = (r, c)
while stack:
cr, cc = stack.pop()
value = grid[cr][cc]
total += value
if value < 0:
nonneg = False
first = min(first, (cr, cc))
last = max(last, (cr, cc))
for nr, nc in ((cr - 1, cc), (cr + 1, cc), (cr, cc - 1), (cr, cc + 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != 0 and not seen[nr][nc]:
seen[nr][nc] = True
stack.append((nr, nc))
cand = (total, last, first)
if best_all is None or (cand[0], cand[1]) > (best_all[0], best_all[1]):
best_all = cand
if nonneg and (best_nonneg is None or (cand[0], cand[1]) > (best_nonneg[0], best_nonneg[1])):
best_nonneg = cand
def fmt(cand):
if cand is None:
return {"sum": None, "index": None, "last_index": None}
total, last, first = cand
return {"sum": total, "index": [first[0], first[1]], "last_index": [last[0], last[1]]}
return {"all": fmt(best_all), "nonnegative": fmt(best_nonneg)}