Battleships in a Board in C++


Suppose we have an 2D board, we have to count how many battleships are in it. The battleships are represented with the symbol 'X', empty slots are represented with '.'s. We can assume these 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.

So if the board is like:

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

Then the output will be 2, as there are two battleships.

To solve this, we will follow these steps −

  • ans := 0, n := row count and m := column count

  • for ith row

    • for jth column

      • if board[i, j] is dot, then go for the next iteration

      • if i > 0 and board[i – 1, j] = ‘X’, then go for the next iteration

      • if j > 0 and board[i, j - 1] = ‘X’, then go for the next iteration

      • increase ans by 1

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int countBattleships(vector<vector<char>>& board) {
      int ans = 0;
      int n = board.size();
      int m = board[0].size();
      for(int i = 0; i < n; i++){
         for(int j = 0; j < m; j++){
            if(board[i][j] == '.')continue;
            if(i > 0 && board[i - 1][j] == 'X')continue;
            if(j > 0 && board[i][j - 1] == 'X')continue;
            ans++;
         }
      }
      return ans;
   }
};
main(){
   vector<vector<char>> v = {{'X','.','.','X'},{'.','.','.','X'},{'.','.','.','X'}};
   Solution ob;
   cout << (ob.countBattleships(v));
}

Input

[["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]

Output

2

Updated on: 30-Apr-2020

636 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements