A pixel-art editor has a "count shapes" feature. The canvas is a grid of 0 (empty) and 1 (painted) cells. Painted cells that touch horizontally or vertically belong to the same shape; diagonal contact doesn't count.
Write countIslands(grid), which returns the number of separate shapes.
countIslands([
[1, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 1],
]);
// 4: top-left blob, top-right blob, the lone centre cell, the bottom-right cell
countIslands([
[1, 0],
[0, 1],
]);
// 2 (diagonal neighbours are separate shapes)
countIslands([]); // 0
countIslands([[0]]); // 0
grid; the editor still needs it.Spotted a mistake or a rights concern? Report an issue