All problems
0956MediumArrayDepth-First SearchMatrix

Counting Vessels on the Chart

Tracked in this browser only
Write code

Trains the technique from

LeetCode 419Battleships in a Board

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A chart is given as board, each cell holding '.' for open water or 'X' for part of a vessel.

Every vessel lies in a single straight line, either along one row or down one column, and occupies a run of neighbouring cells. No two vessels touch, so between any two of them there is at least one cell of open water.

Return how many vessels are on the chart.

Examples

Example 1

Input
board = [["X", ".", ".", "X"], [".", ".", ".", "X"], [".", ".", ".", "X"], ["X", "X", ".", "."]]
Output
3

There is a single cell at the top left, a run of three down the last column, and a run of two along the bottom row, which is three vessels.

Example 2

Input
board = [["X", "X", "X"]]
Output
1

The three cells form one vessel lying along the row, counted once at its left-hand end.

Example 3

Input
board = [[".", ".", "."], [".", ".", "."], [".", ".", "."]]
Output
0

The chart is all open water.

Constraints

  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • Every row of board has the same length
  • board[i][j] is either '.' or 'X'

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def count_battleships(board: list[list[str]]) -> int:
Java
public int countBattleships(char[][] board)
September 7
Apply