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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code