Battleships In A Board
To solve this coding challenge, the goal is to count the number of distinct battleships on a given m x n board without modifying the board and using O(1) extra memory.
A battleship is represented by a series of contiguous 'X' cells that are either aligned horizontally or vertically, and no two battleships are adjacent to each other. This means that between any two battleships, there should be at least one '.' cell.
Explanation
The primary trick is to traverse the board and identify the starting cell of each battleship. A cell is considered the starting cell of a battleship if:- It contains an 'X'.
- The cell above it (if it exists) does not contain an 'X'.
- The cell to the left of it (if it exists) does not contain an 'X'. By ensuring these conditions, each 'X' will only be counted once per battleship, effectively eliminating any redundancy in counting.
- Initialize a counter variable to zero.
- Iterate over each row of the board.
- Within each row, iterate over each cell.
- For each cell that contains an 'X':
- Check if it is the starting cell of a battleship (i.e., ensure that neither the cell above it nor the cell to the left of it has an 'X').
- If it is the starting cell, increment the counter.
- Return the counter as the result.
Detailed Steps in Pseudocode
Pseudocode
# Initialize a function to count battleships on the board
function countBattleships(board):
# Initialize a counter for battleships
battleship_count = 0
# Iterate through each row index in the board
for row_index in range(0, length(board)):
# Iterate through each column index in the board
for col_index in range(0, length(board[row_index])):
# Check if the current cell contains an 'X'
if board[row_index][col_index] == 'X':
# Check if there is a cell above the current cell and if that cell contains an 'X'
if row_index > 0 and board[row_index - 1][col_index] == 'X':
# If true, it means this 'X' is part of a vertically continuing battleship, so continue to the next iteration
continue
# Check if there is a cell to the left of the current cell and if that cell contains an 'X'
if col_index > 0 and board[row_index][col_index - 1] == 'X':
# If true, it means this 'X' is part of a horizontally continuing battleship, so continue to the next iteration
continue
# If the current 'X' is the starting point of a battleship, increment the battleship counter
battleship_count += 1
# Return the total count of battleships
return battleship_count
This pseudocode ensures that we scan the board in one pass, using only O(1) extra memory for the counter and a few variables for indexing and condition checking. This adheres to the constraints provided and meets the requirements of the challenge efficiently.