Skip to content
Problem 419 · LeetCode 419(opens in a new tab)

Battleships in a Board

MediumArrays

You are given a grid board where each cell is either "X", part of a ship, or ".", open water. Every ship is a straight line of cells: one row tall or one column wide, of any length.

Two ships never share a side: some water always separates them up, down, left and right. Return how many ships are on the board.

Example 1

Input:  board = [["X","X",".","X"],
                 [".",".",".","X"],
                 ["X",".",".","."]]
Output: 3
Why:    a 2-cell ship on top, a 2-cell ship down the right side, and a 1-cell ship
2 more examples and the constraints

Example 2

Input:  board = [["X"]]
Output: 1
Why:    a ship can be a single cell

Example 3

Input:  board = [[".","."],[".","."]]
Output: 0
Why:    only water

Constraints

  • 1 ≤ rows, columns ≤ 200
  • Every cell is "X" or "."
  • The board is always valid: ships are straight and never side by side
  • Follow-up: one pass, O(1) extra memory, without changing the board

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Flood fill each shipO(m·n)
  2. Count top-left cellsO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 200 × 200 boardVerdict
Flood fill each shipO(m·n)
Passes; extra memory
Count top-left cellsO(m·n)
Best; one pass, O(1) space

m = rows, n = columns.

Edge cases to test

  • No ships. An all-water board returns 0.
  • Single-cell ships. [["X"]] is one ship; its top-left cell is itself.
  • Ships on the first row or column. There is no cell above or to the left, so check the bounds before reading it.
  • Corners touching. Ships may meet diagonally, as in X.X / .X. / X.X: that is 5 ships, since only up and left are checked.

Common mistakes

  • Reading board[r - 1][c] on the first row (or board[r][c - 1] on the first column) without a bounds check.
  • Also checking the cells below and to the right, which wrongly skips the first cell of a ship.
  • Writing over the board to mark visited cells when the follow-up says to leave it unchanged.

How to talk through it

  1. 1Clarify. Are ships always straight? Can two ships share a side? May I change the board?
  2. 2Start with flood fill. Count connected groups of X like islands; O(m·n) time but O(m·n) memory.
  3. 3Use the shape. A straight ship that touches no other has one cell with no X above or left.
  4. 4Code the one pass. Skip water, skip X with an X above or left, count the rest. Mind the bounds.
  5. 5Test out loud. Run an empty board, a single cell, and ships on the top row and left column.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?