Battleships in a Board (LeetCode 419): Solution and Explanation
A grid holds straight battleships made of 'X' cells, separated from each other by at least one empty cell horizontally and vertically. Count how many battleships there are.
Intuition
The obvious idea is to flood fill: every time you find an unvisited 'X', count a ship and mark all its cells. That works, but it needs a visited marker or modifies the board.
Ships are straight lines, so every ship has exactly one top-left cell. Call it the head. If you count heads, you count ships, one for one.
Recognising a head is a purely local test. The head is the only cell of its ship with no 'X' directly above it and no 'X' directly to its left. Every other cell of a vertical ship has an 'X' above, and every other cell of a horizontal ship has an 'X' to the left.
Because ships never touch side by side, an 'X' above or to the left can only belong to the same ship. Diagonal neighbours do not matter, since the test only looks straight up and straight left.
Approach: Count ship heads in one pass
- Set
count = 0. - Visit every cell in row-major order.
- Skip the cell if it is water.
- Skip it if the cell above is 'X': it continues a vertical ship that was counted higher up.
- Skip it if the cell to the left is 'X': it continues a horizontal ship that was counted further left.
- Otherwise it is a head, so add 1. Return
countat the end.
Step-by-step example
board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
- (0,0) is 'X' with nothing above and nothing to its left: a head, count = 1.
- (0,1) and (0,2) are water. (0,3) is 'X'; the cell to its left is water and there is no row above, so it is a head, count = 2.
- Row 1: only (1,3) is 'X', and (0,3) above it is 'X', so it belongs to ship #2. Skip.
- Row 2: (2,3) has 'X' above as well. Skip.
- The scan ends with count = 2.
Code: Python, Java, C++
1class Solution:
2 def countBattleships(self, board: List[List[str]]) -> int:
3 count = 0
4 for r in range(len(board)):
5 for c in range(len(board[0])):
6 if board[r][c] != 'X':
7 continue
8 if r > 0 and board[r - 1][c] == 'X':
9 continue
10 if c > 0 and board[r][c - 1] == 'X':
11 continue
12 count += 1
13 return count1class Solution {
2 public int countBattleships(char[][] board) {
3 int count = 0;
4 for (int r = 0; r < board.length; r++) {
5 for (int c = 0; c < board[0].length; c++) {
6 if (board[r][c] != 'X') continue;
7 if (r > 0 && board[r - 1][c] == 'X') continue;
8 if (c > 0 && board[r][c - 1] == 'X') continue;
9 count++;
10 }
11 }
12 return count;
13 }
14}1class Solution {
2public:
3 int countBattleships(vector<vector<char>>& board) {
4 int count = 0;
5 for (int r = 0; r < board.size(); r++) {
6 for (int c = 0; c < board[0].size(); c++) {
7 if (board[r][c] != 'X') continue;
8 if (r > 0 && board[r - 1][c] == 'X') continue;
9 if (c > 0 && board[r][c - 1] == 'X') continue;
10 count++;
11 }
12 }
13 return count;
14 }
15};Time and space complexity
O(m x n)
Each cell is visited once and looks at no more than two neighbours.
O(1)
Only the counter is stored, and the board is never modified.
Other approaches
Flood fill (DFS or BFS) (time O(m x n), space O(m x n))
For each unvisited 'X', count one ship and mark every connected 'X'. It is the general method for counting connected shapes, but it needs a visited set or overwrites the board, and the recursion can be deep for long ships.
Walk each ship to its end (time O(m x n), space O(1) if the board may be changed)
When you find a head, step right or down to mark the whole ship. Same idea as flood fill, specialised for straight ships, still writes to the board.
Common mistakes
- Skipping an 'X' when any of its four neighbours is 'X'. The head of a ship longer than one cell has an 'X' below it or to its right, so it would be skipped and the ship never counted. Only look up and left.
- Forgetting the bounds checks
r > 0andc > 0. In Python,board[-1]silently reads the last row. - Comparing against the wrong character. Cells are the characters 'X' and '.', not numbers or strings like "1".
Frequently asked questions
Why does counting heads give the number of ships?
Each ship is a straight line, so it has exactly one cell with no part of itself above or to the left. No other cell passes that test, and ships are separated, so a neighbouring 'X' always belongs to the same ship.
Does this solve the follow-up?
Yes. It is a single pass, uses one counter, and only reads the board.
What if two ships touch diagonally?
That is allowed and does not break the method, because the head test only looks straight up and straight left, never diagonally.
Would the trick work for bent shapes like islands?
No. A bent shape can have several cells with nothing above or left of them, so you would overcount. For general shapes use a flood fill, as in Number of Islands.