Skip to the code
cf.
+50 XP

#458 Shape Count After Each Click

hard

A pixel editor starts with an empty canvas of rows by cols cells. Each click in clicks is a [row, col] that fills that cell with ink. Clicking a cell that is already filled does nothing. Filled cells that touch up, down, left, or right belong to the same shape.

Write shapesAfterClicks(rows, cols, clicks) that returns an array with the number of shapes on the canvas after each click. The canvas can be huge, so don't recount the whole canvas each time.

Example 1

Input: rows = 3, cols = 3, clicks = [[0,0],[0,1],[1,2],[2,1],[1,1]]
Output: [1,1,2,3,1]

The last click at the center touches (0, 1), (1, 2), and (2, 1), joining all three shapes into one.

Example 2

Input: rows = 1, cols = 2, clicks = [[0,0],[0,0]]
Output: [1,1]

Clicking a filled cell again changes nothing.

Constraints

  • 1 <= rows, cols <= 10000
  • rows * cols <= 10^6
  • 0 <= clicks.length <= 10^5
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).