Leetcode 419. Battleships in a Board
You are given an m x n board 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 the board. In other words, they can only be placed in the following shapes:
XXX
X
X
X
Battleships should not be placed adjacent to each other, meaning no two battleships will share a side.
board = [
["X", ".", ".", "X"],
[".", ".", ".", "X"],
[".", ".", ".", "X"]
]
Output: 2
#include <vector>
using namespace std;
class Solution {
public:
int countBattleships(vector<vector<char>>& board) {
if (board.empty() || board[0].empty()) return 0;
int m = board.size();
int n = board[0].size();
int count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == 'X') {
if (i > 0 && board[i-1][j] == 'X') continue;
if (j > 0 && board[i][j-1] == 'X') continue;
count++;
}
}
}
return count;
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?