

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Questions & Answers
- Add a new board in Arduino
- Domino Covering Board in Python
- Change board selection in Arduino IDE
- Minimum Cost to cut a board into squares in C++
- Minimum Cost to cut a board into squares in Python
- How to program a board using Arduino IDE
- Components of Arduino Uno board
- Printed Circuit Board (PCB) Motors
- Check if the board is connected or not in Arduino IDE
- C++ code to find score of winning square on a square board
- Program to check whether a board is valid N queens solution or not in python
- Program to check words can be found in matrix character board or not in Python
- Program to find next board position after sliding the given direction once in Python
- SAT – The Undergraduate College Admissions Test by the College Board
- Python program to print check board pattern of n*n using numpy