Problem Description
Given an m x n board, count the number of battleships on the board. Each battleship is represented by contiguous 'X's placed either horizontally or vertically. Battleships are separated by at least one empty cell ('.') in all directions, so if an 'X' has another 'X' above or to its left, it is part of an already counted battleship.
Key Insights
- A battleship is represented as a contiguous line (either 1 x k or k x 1) of 'X's.
- Since battleships are not adjacent, you can count an 'X' only if there is no 'X' directly above or to the left.
- This check ensures that you count the battleship only once, at its "start" cell.
Space and Time Complexity
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Space Complexity: O(1) as no additional data structures are used.
Solution
Traverse the board once. For each cell:
- If the cell contains '.', continue.
- If the cell contains 'X', check:
- If there is an 'X' directly above, it is part of an already counted vertical battleship.
- If there is an 'X' directly to the left, it is part of an already counted horizontal battleship.
- Only increment your counter for battleships if both conditions are false.
- This one-pass solution satisfies the requirement of constant extra space and no modification to the board.