AlgoDaily

Count the Planes

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

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:

[
  ['.', '.', '.', 'P'],
  ['.', '.', '.', 'P'],
  ['P', 'P', '.', 'P'],
  ['.', '.', '.', 'P']
]

Within that matrix, the dots (.s) represent available airspace. The Ps 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 Ps 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.

[
  ['.', '.', 'P'],
  ['.', 'P', '.'],
  ['P', '.', '.']
]

Could you accomplish this in one pass?

sky = [
  ['.', '.', '.', 'P'],
  ['.', '.', '.', 'P'],
  ['P', 'P', '.', 'P'],
  ['.', '.', '.', 'P']
]

numOfPlanes(sky);
// 2
Constraints
  • Total number of elements in the matrix <= 100000
  • The elements will consist only of . and P characters
  • The matrix can be empty
  • Expected time complexity : O(n * m) where n and m are number of rows and columns respectively
  • Expected space complexity : O(1)
```js
function numOfPlanes(grid) {
  // fill this in
  return grid;
}
```

```java
public class Main {
    public static int numOfPlanes(int[][] grid) {
        // fill this in
        return grid;
    }
    
    public static void main(String[] args) {
        // Driver code
    }
}
```
```javascript
function numOfPlanes(grid) {
    // fill this in
    return grid;
}
```
```python
def numOfPlanes(grid):
    # fill this in
    return grid

# Driver code
```
```cpp
#include <vector>

int numOfPlanes(std::vector<std::vector<int>>& grid) {
    // fill this in
    return grid;
}

int main() {
    // Driver code
    return 0;
}
```
```csharp
public class Program {
    public static int numOfPlanes(int[][] grid) {
        // fill this in
        return grid;
    }
    
    public static void Main() {
        // Driver code
    }
}
```
```go
package main

import "fmt"

func numOfPlanes(grid [][]int) int {
    // fill this in
    return grid
}

func main() {
    // Driver code
}
```

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →