#419

Battleships in a Board

Medium
ArrayDepth-First SearchMatrixArrayMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n)
O(m * n)
Space
O(1)
O(1)
💡

Intuition

Time O(m * n)Space O(1)

The optimal solution also involves scanning the board, but it counts battleships in a single pass while ensuring that we only count the starting cell of each battleship. This is efficient because we avoid unnecessary checks after finding a battleship's starting point.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Loop through each cell in the board.
  3. 3Step 3: When an 'X' is found, check if it's the first 'X' in its row or column. If so, increment the counter.
  4. 4Step 4: Continue until all cells are processed.
  5. 5Step 5: Return the counter as the number of battleships.
solution.py9 lines
1def countBattleships(board):
2    if not board:
3        return 0
4    count = 0
5    for i in range(len(board)):
6        for j in range(len(board[0])):
7            if board[i][j] == 'X' and (i == 0 or board[i-1][j] == '.') and (j == 0 or board[i][j-1] == '.'):
8                count += 1
9    return count

Complexity note: The time complexity remains O(m * n) as we still need to check each cell. The space complexity is O(1) since we are only using a few variables for counting.

  • 1Battleships are separated by at least one cell, which allows us to only count the starting cells.
  • 2We can efficiently count battleships by checking only the first 'X' in each row and column.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.