Formatted question description:

419. Battleships in a Board




Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:

  • You receive a valid board, made of only battleships or empty slots.
  • Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
  • At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.



In the above board there are 2 battleships.

Invalid Example:


This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:

Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?


Since there are no adjacent battleships, all cells with 'X's that are connected represent the same battleship.

Use another 2D array to store whether a cell is visited. Loop over the board. If the current cell is 'X' and is not visited, then set the current cell to visited, and set the states of all the cells in the same row and the same column that are connected to the current cell to visited. Add the counter by 1.

Finally, return the counter.

  • class Solution {
        public int countBattleships(char[][] board) {
            int rows = board.length, columns = board[0].length;
            boolean[][] visited = new boolean[rows][columns];
            int count = 0;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    if (visited[i][j] || board[i][j] == '.')
                    visited[i][j] = true;
                    for (int k = i - 1; k >= 0 && board[k][j] == 'X'; k--)
                        visited[k][j] = true;
                    for (int k = i + 1; k < rows && board[k][j] == 'X'; k++)
                        visited[k][j] = true;
                    for (int k = j - 1; k >= 0 && board[i][k] == 'X'; k--)
                        visited[i][k] = true;
                    for (int k = j + 1; k < columns && board[i][k] == 'X'; k++)
                        visited[i][k] = true;
            return count;
  • Todo
  • class Solution(object):
      def countBattleships(self, board):
        :type board: List[List[str]]
        :rtype: int
        ans = 0
        for i in range(0, len(board)):
          for j in range(0, len(board[0])):
            if board[i][j] == "X" and (i == 0 or board[i - 1][j] != "X") and (j == 0 or board[i][j - 1] != "X"):
              ans += 1
        return ans

All Problems

All Solutions