Battleships in a Board

Medium

Topics
ArrayDFSMatrix

Given an m x n board where each cell is either 'X' (part of a battleship) or '.' (empty), return the number of battleships. Battleships are placed horizontally or vertically, and no two battleships are adjacent (there is at least one empty cell between them).

Example 1

0X..X1...X2...X0123
Each shaded run of Xs is one ship, always a straight line of one row or one column. Because ships never touch, a ship can be counted by its top-left cell alone — no flood fill needed. There are 2.
Character grid — one row per line.
Input:  board = ["X..X","...X","...X"]
Output: 2

Example 2

0.0
Input:  board = ["."]
Output: 0

Constraints

  • 1 <= m, n <= 200
  • board[i][j] is 'X' or '.'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Ships are horizontal or vertical runs of 'X', separated by at least one '.'. The instinct is to flood-fill each ship and count components, which needs a visited set or destructive marking.

Neither is necessary. Count each ship exactly once by counting only its head — the cell that has no 'X' above it and none to its left. Every ship, being a straight run, has exactly one such cell: its top for a vertical ship, its left end for a horizontal one.

So one sweep, two neighbour checks per cell, no extra memory and no mutation of the input.

Approach

  1. For each cell containing 'X', count it if the cell above is out of bounds or not 'X', and likewise to the left.

Dry Run

board    X . . X
         . . . X
         . . . X

(0,0) X: nothing above (edge), nothing left (edge)   -> count 1
(0,3) X: nothing above (edge), left is '.'           -> count 2
(1,3) X: above is X                                   -> not a head
(2,3) X: above is X                                   -> not a head

answer 2

Complexity

  • Time — O(m*n): every cell visited once with constant work.
  • Space — O(1): a counter. Flood fill would need O(m*n) for the visited grid plus a stack, or would have to destroy the input.

Common Pitfalls

  • Reaching for DFS or BFS. It works, but it costs memory for information two neighbour checks already provide.
  • Checking all four neighbours. Only up and left matter; checking down or right would reject the head.
  • Indexing before the bounds check at row 0 or column 0.
  • Assuming ships might touch or bend. The problem guarantees they are straight and separated, which is exactly what makes the one-head-per-ship argument hold — without that guarantee this method is unsound.

Full Solution — all languages

class Solution:
    def countBattleships(self, grid):
        R, C = len(grid), len(grid[0])
        cnt = 0
        for r in range(R):
            for c in range(C):
                if grid[r][c] == 'X' and (r == 0 or grid[r-1][c] != 'X') and (c == 0 or grid[r][c-1] != 'X'):
                    cnt += 1
        return cnt
SensAI
Beta
Tap the mic to stop voice mode