Skip to main content

Battleships in a Board

LeetCode 419 | Difficulty: Medium​

Medium

Problem Description​

Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.

Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).

Example 1:

Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2

Example 2:

Input: board = [["."]]
Output: 0

Constraints:

- `m == board.length`

- `n == board[i].length`

- `1 <= m, n <= 200`

- `board[i][j]` is either `'.'` or `'X'`.

Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?

Topics: Array, Depth-First Search, Matrix


Approach​

Matrix​

Treat the matrix as a 2D grid. Common techniques: directional arrays (dx, dy) for movement, BFS/DFS for connected regions, in-place marking for visited cells, boundary traversal for spiral patterns.

When to use

Grid traversal, island problems, path finding, rotating/transforming matrices.


Solutions​

Solution 1: C# (Best: 92 ms)​

MetricValue
Runtime92 ms
Memory39 MB
Date2022-02-14
Solution
public class Solution {
public int CountBattleships(char[][] board) {
int m = board.Length;
int n = board[0].GetLength(0);
bool[,] used = new bool[m,n];
int ships = 0;

for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (board[i][j] == 'X' && !used[i,j])
{
Dfs(board, i, j, m, n, used);
ships++;
}
}
}
return ships;
}

private void Dfs(char[][] board, int i, int j, int m, int n,bool[,] used)
{
List<int[]> dirs = new List<int[]>() {
new int[] {1, 0},
new int[] {0, 1}
};
foreach (var dir in dirs)
{
int x = i + dir[0];
int y = j + dir[1];
if (x < 0 || x >= m || y < 0 || y >= n || used[x, y] || board[x][y] != 'X') continue;
while (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'X')
{
used[x, y] = true;
x = x + dir[0];
y = y + dir[1];
}
break;
}
}
}

Complexity Analysis​

ApproachTimeSpace
Graph BFS/DFS$O(V + E)$$O(V)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.