Graphs · Problem 1 of 3

Count the parks on a city map

Pattern: Number of Islands: Count Regions in a Grid

mediumNot solved yet

The problem

A city map is a grid given as a list of equal-length strings. "P" is a park cell and "." is anything else. Park cells that touch up, down, left or right belong to the same park (diagonal doesn't count). Write a function that returns how many separate parks there are.

text
1count_parks(["PP..", "P..P", "..PP"])  ->  2
2count_parks(["P.P", ".P.", "P.P"])     ->  5
3count_parks([])                        ->  0
Example 1
111222

Two parks. Cells belong together only when they touch up, down, left or right.

In the second example, the cells only touch diagonally, so each one is its own park.

Write count_parks(city) in Python or countParks(city) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 20 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.