Battleships in a Board

You are given an `m x n` board where each cell is a battleship part `'X'` or empty `'.'`. Return the number of battleships on the board. A battleship is a straight line of `'X'` cells, either `1 x k` (horizontal) or `k x 1` (vertical). No two battleships touch horizontally or vertically: at least one empty cell separates them. **Follow up:** can you do it in one pass, with O(1) extra memory and without changing the board?

30:00

Battleships in a Board
medium
Free written solution
Topics
Companies

You are given an m x n board where each cell is a battleship part 'X' or empty '.'. Return the number of battleships on the board.

A battleship is a straight line of 'X' cells, either 1 x k (horizontal) or k x 1 (vertical). No two battleships touch horizontally or vertically: at least one empty cell separates them.

Follow up: can you do it in one pass, with O(1) extra memory and without changing the board?

Example 1:
Input: {"board":[["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]}
Output: 2
Constraints:
  • m==board.lengthm == \text{board.length}

  • n==board[i].lengthn == \text{board}[i].\text{length}

  • 1≤m,n≤2001 \leq m, n \leq 200

  • board[i][j]\text{board}[i][j] is either 'X' or '.'

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"board":[["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]}

count = 0. Scan row by row. A ship is counted only at its head: the X with no X directly above it and no X directly to its left.

# = ship head (counted), arrows point to the part that already counted the ship

ships counted

0

this cell

start scanning

Variables
VariableValue
count0
DepthFunction Call
Stack empty
0/16