class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
if not board or not board[0]:
return 0
rows, cols = len(board), len(board[0])
count = 0
for i in range(rows):
for j in range(cols):
if board[i][j] == 'X':
if (i == 0 or board[i-1][j] != 'X') and (j == 0 or board[i][j-1] != 'X'):
count += 1
return count
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
int rows = board.size(), cols = board[0].size();
int count = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (board[i][j] == 'X') {
if ((i == 0 || board[i-1][j] != 'X') && (j == 0 || board[i][j-1] != 'X')) {
++count;
}
}
}
}
return count;
}
};
class Solution {
public int countBattleships(char[][] board) {
int rows = board.length, cols = board[0].length;
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'X') {
if ((i == 0 || board[i-1][j] != 'X') && (j == 0 || board[i][j-1] != 'X')) {
count++;
}
}
}
}
return count;
}
}
var countBattleships = function(board) {
let rows = board.length, cols = board[0].length;
let count = 0;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (board[i][j] === 'X') {
if ((i === 0 || board[i-1][j] !== 'X') && (j === 0 || board[i][j-1] !== 'X')) {
count++;
}
}
}
}
return count;
};
'X'
(part of a battleship) or '.'
(empty water). Each battleship occupies consecutive cells either horizontally or vertically, and there are no adjacent battleships (i.e., there are never two battleships touching each other horizontally or vertically). Your task is to count how many distinct battleships are present on the board.
Key constraints:
'X'
cells, aligned either horizontally or vertically.'.'
(water) in all directions.'X'
cell, perform a depth-first or breadth-first search to mark all connected 'X'
cells as part of the same battleship, and count each time a new, unvisited 'X'
is found. However, this requires extra space to track visited cells or modifies the board, which isn't optimal.
On further thought, since the problem guarantees that battleships are not adjacent, we can optimize. Instead of marking and visiting, we can recognize that the start of every battleship is the top-leftmost cell in its segment: it will not have another 'X'
directly above or to its left. Thus, we only need to count these unique starting points to get the total number of battleships.
'X'
, check if it is the top-leftmost part of a battleship:
'X'
directly above (i-1, j
), then this cell is part of a vertical battleship already counted.'X'
directly to the left (i, j-1
), then this cell is part of a horizontal battleship already counted.X . . X . . . X . . . XLet's walk through each cell:
'X'
cell with no 'X'
above or to the left. By counting only these, we efficiently solve the problem in one pass, with no extra memory or modification to the board. This makes the solution both elegant and optimal.