FastPrepCount Battleships by Size

Count Battleships by Size

Deloitte logoDeloitte● EasyFULLTIMEOA
Learn

Problem statement

You are given a rectangular Battleship board as an array of equal-length strings grid:

  • # is part of a ship.
  • . is water.

Each ship is one maximal group of # cells connected vertically or horizontally. Every ship is guaranteed to be a straight horizontal or vertical segment of length 1, 2, or 3. Distinct ships do not touch vertically or horizontally, although they may touch diagonally.

Return an integer array [single, double, triple], where:

  • single is the number of length-1 ships.
  • double is the number of length-2 ships.
  • triple is the number of length-3 ships.

Function

countShipTypes(grid: String[]) → int[]

Examples

Example 1

grid = ["#..##.","......","###...","......"]return = [1,1,1]

The board contains one isolated cell, one horizontal ship of length 2, and one horizontal ship of length 3.

Example 2

grid = ["#.#","..#","..#","...","##."]return = [1,1,1]

The board contains a single-cell ship, a horizontal length-2 ship, and a vertical length-3 ship.

Example 3

grid = ["#.#.#","..#.#","....#","##...","....."]return = [1,2,1]

There is one length-1 ship, two length-2 ships, and one length-3 ship. Diagonal contact does not merge ships.

Constraints

  • 1 <= grid.length <= 500.
  • 1 <= grid[i].length <= 500.
  • Every row has the same length.
  • Every cell is # or ..
  • Every maximal orthogonally connected ship is a straight segment of length 1, 2, or 3.

More Deloitte problems

See Deloitte hiring insights
public int[] countShipTypes(String[] grid) {
    // Write your code here.
}
grid["#..##.","......","###...","......"]
expected[1,1,1]
Checking account…