Formatted question description: https://leetcode.ca/all/419.html

# 419. Battleships in a Board

Medium

## Description

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.

Example:

X..X
...X
...X


In the above board there are 2 battleships.

Invalid Example:

...X
XXXX
...X


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

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

## Solution

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] == '.')
continue;
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;
count++;
}
}
return count;
}
}