The "Battleships in a Board interview question" is a matrix-based counting problem. You are given a 2D grid representing a sea, where 'X' represents a part of a battleship and '.' represents open water. Battleships can only be placed horizontally or vertically and are separated by at least one horizontal or vertical cell of water. Your task is to count the total number of ships without using extra memory or modifying the original board.
Companies like Microsoft and Meta use the "Battleships in a Board coding problem" to test a candidate's ability to find "head" or "representative" elements in a grid. While you could use "Depth-First Search interview pattern" to find connected components, the real test is whether you can find a more efficient space solution by identifying a unique property of each ship.
The most efficient solution uses a Single Pass with Boundary Checking. Instead of traversing the entire ship when you find an 'X', you only count the "top-left" corner of the ship.
Board:
X . . X
X . . X
. . . X
r-1 or c-1 is out of bounds before accessing the array.When asked to count connected components in a grid with strict shapes (like horizontal/vertical only), always look for a "one-pass" strategy. Identifying a unique part of the shape (like the top-left corner) is a powerful "Matrix interview pattern" trick that avoids complex traversals.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find All Groups of Farmland | Medium | Solve | |
| Minesweeper | Medium | Solve | |
| Pacific Atlantic Water Flow | Medium | Solve | |
| Coloring A Border | Medium | Solve | |
| Shortest Bridge | Medium | Solve |