Battleships in a Board - Problem

Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of battleships on the board.

Battleships can only be placed horizontally or vertically on the board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size.

At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).

Input & Output

Example 1 — Mixed Battleships
$ Input: board = [["X",".",".","X"],[".",...,".","X"],[".",...,".","X"]]
Output: 2
💡 Note: First battleship is single cell at (0,0). Second battleship is vertical at positions (0,3), (1,3), (2,3). Total count is 2.
Example 2 — Single Ship
$ Input: board = [["X"]]
Output: 1
💡 Note: Single cell battleship at position (0,0). Total count is 1.
Example 3 — No Ships
$ Input: board = [["."]]
Output: 0
💡 Note: No battleship cells found in the grid. Total count is 0.

Constraints

  • m == board.length
  • n == board[i].length
  • 1 ≤ m, n ≤ 200
  • board[i][j] is either '.' or 'X'

Visualization

Tap to expand
Battleships in a Board INPUT X . . X . . . X . . . X 3x4 Board Matrix = Battleship 1 (horizontal) = Battleship 2 (vertical) board = [["X",".",".","X"], [".",".",".","X"], [".",".",".","X"]] ALGORITHM STEPS 1 Scan each cell Iterate through board 2 Find 'X' cells Check if cell is battleship 3 Check Top-Left No X above or left? 4 Count as new ship Increment counter ? X ? check check If no X above and no X left = NEW SHIP! Time: O(m*n) | Space: O(1) Single pass, no extra memory FINAL RESULT X 1 . . X 2 . . . X . . . X Ship 1: (0,0) 1x1 horizontal Ship 2: (0,3)-(2,3) 3x1 vertical OUTPUT 2 2 battleships detected by counting top-left corners Key Insight: Top-Left Corner Detection Instead of marking visited cells or using DFS, count only the TOP-LEFT corner of each battleship. A cell is a top-left corner if: (1) It contains 'X', (2) No 'X' directly above, (3) No 'X' directly left. This guarantees O(1) space and single-pass O(m*n) time - each battleship is counted exactly once! TutorialsPoint - Battleships in a Board | Top-Left Corner Detection Approach
Asked in
Microsoft 15 Apple 12
85.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen