Skip to the code
cf.
+10 XP

#421 Count Shapes on a Canvas

easy

A whiteboard app exports a rough bitmap of the board as a grid of strings: "#" is ink and "." is empty. Ink cells that touch up, down, left, or right belong to the same shape. Diagonal touching doesn't count.

Write countShapes(board) that returns the number of separate shapes.

Example 1

Input: board = ["##..","#..#","..##"]
Output: 2

The three cells in the top-left form one shape, and the three in the bottom-right form another.

Example 2

Input: board = ["#.#",".#.","#.#"]
Output: 5

The cells only touch diagonally, so each is its own shape.

Constraints

  • 1 <= board.length, board[i].length <= 200
  • Each cell is "#" or ".".
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).