Good morning! Here's our prompt for today.
Assume that we are building software to determine how many planes are in the sky.

The data that we have on planes currently in the air comes in the form of a grid, modeled by a matrix array. See below:
1[
2 ['.', '.', '.', 'P'],
3 ['.', '.', '.', 'P'],
4 ['P', 'P', '.', 'P'],
5 ['.', '.', '.', 'P']
6]
Within that matrix, the dots (.
s) represent available airspace. The P
s that are neighboring each other model one plane each. So in the above example, there are exactly 2
planes.
Given a multi-dimensional array of .
s and P
s exclusively, can you find the number of planes that there are in the sky? Planes may only be placed horizontally or vertically. A diagonal plane like this would not count as one plane. Instead, there will be 3 separate planes.
1[
2 ['.', '.', 'P'],
3 ['.', 'P', '.'],
4 ['P', '.', '.']
5]
Could you accomplish this in one pass?
1sky = [
2 ['.', '.', '.', 'P'],
3 ['.', '.', '.', 'P'],
4 ['P', 'P', '.', 'P'],
5 ['.', '.', '.', 'P']
6]
7
8numOfPlanes(sky);
9// 2
Constraints
- Total number of elements in the matrix <=
100000
- The elements will consist only of
.
andP
characters - The matrix can be empty
- Expected time complexity :
O(n * m)
wheren
andm
are number of rows and columns respectively - Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
​
def num_of_planes(grid):
# fill in
return num_of_ships
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert num_of_planes([]) == 0
print("PASSED: assert num_of_planes([]) == 0")
​
def test_2(self):
assert (
num_of_planes(
[
[".", ".", ".", "P"],
[".", ".", ".", "P"],
["P", "P", ".", "P"],
[".", ".", ".", "P"],
]
)
== 2
)
print(
"PASSED: assert num_of_planes([ ['.', '.', '.', 'P'], ['.', '.', '.', 'P'], ['P', 'P', '.', 'P'], ['.', '.', '.', 'P'] ]) == 2"
)
​
Here's a video of us explaining the solution.
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.