- Related Questions & Answers
- Minimum Cost to cut a board into squares in C++
- Domino Covering Board in Python
- Minimum Cost to cut a board into squares in Python
- Program to check whether a board is valid N queens solution or not in python
- SAT – The Undergraduate College Admissions Test by the College Board
- Program to find next board position after sliding the given direction once in Python
- Python program to print check board pattern of n*n using numpy
- How did Mercedes Fleet-board Technology brings the First all-electric Truck?
- Program to find the percentage of places where knight can move and not left the board in Python
- Reverse a string in C/C++
- A C Puzzle in C Programming?
- A-Buffer Method in C/C++?
- How a Preprocessor works in C/C++?
- A comma operator question in C/C++ ?
- A Number Link Game in C/C++?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

#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)); }

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

2

Advertisements