0419. Battleships in a Board

419. Battleships in a Board #

Problem #

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:

img

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?

Summary #

Given an m × n matrix called a board, where 'X' in a cell represents a battleship and '.' represents an empty position.

Battleships can only be placed horizontally or vertically on the board (in other words, connected 'X' cells in the same row or the same column are counted as one “battleship group”), and any two “battleship groups” are not adjacent. Return the number of “battleship groups” on the board.

Solution Approach #

The follow-up asks for a one-pass algorithm with O(1) space complexity, without modifying the values in the matrix.

Since the problem states that there is at least one horizontal or vertical empty cell separating any two “battleship groups”, we can count the number of “battleship groups” by enumerating the top-left cell of each battleship.

Suppose the current position in the matrix is an 'X' at (i, j), i.e., board[i][j]='X'. If the current battleship belongs to a new “battleship group”, the following conditions must be satisfied:

  • The cell above the current position is empty, i.e., board[i-1][j]='.';
  • The cell to the left of the current position is empty, i.e., board[i][j-1]='.';

Count all battleship cells whose left and upper neighbors are empty to obtain the number of “battleship groups”.

Code #

package leetcode

func countBattleships(board [][]byte) (ans int) {
	if len(board) == 0 || len(board[0]) == 0 {
		return 0
	}
	for i := range board {
		for j := range board[i] {
			if board[i][j] == 'X' {
				if i > 0 && board[i-1][j] == 'X' {
					continue
				}
				if j > 0 && board[i][j-1] == 'X' {
					continue
				}
				ans++
			}
		}
	}
	return
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文