Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can only have 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 two battleships, so no two battleships are adjacent.
Function Signature
def count_battleships(board: list[list[str]]) -> int:
Rules
-
board
is a list of rows, and each row is a list of one-character strings,
"X"
or
"."
.
-
The board is always valid: every battleship is one straight horizontal or vertical segment, and no two battleships share an edge. Two battleships may touch at a corner (diagonally), and they still count as separate ships.
Constraints
-
m == len(board)
-
n == len(board[i])
-
1 <= m, n <= 200
-
board[i][j]
is either
'.'
or
'X'
.
Examples
Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2
There is a single-cell ship at (0, 0) and a vertical ship covering (0, 3), (1, 3) and (2, 3).
Input: board = [["."]]
Output: 0
The board has no battleships.
Input: board = [["X","X",".","X"],[".",".","X","."],["X",".","X","."]]
Output: 4
The ships are the horizontal pair at (0, 0) and (0, 1), the single cell at (0, 3), the vertical pair at (1, 2) and (2, 2), and the single cell at (2, 0). The ship at (0, 3) touches the one at (1, 2) only at a corner, so they are separate.