- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ code to find center of inner box
Suppose we have a matrix of size n x m. Cells are either 'W' as white or 'B' as black. Some square inside the table with odd length was painted black. We have to find the center of this square.
So, if the input is like
W | W | B | B | B | W |
W | W | B | B | B | W |
W | W | B | B | B | W |
W | W | W | W | W | W |
W | W | W | W | W | W |
then the output will be (3, 1).
Steps
To solve this, we will follow these steps −
n := row count of matrix m := column count of matrix cnt := 0 X := 0 Y := 0 for initialize i := 0, when i < n, update (increase i by 1), do: for initialize j := 0, when j < m, update (increase j by 1), do: if matrix[i, j] is same as 'B', then: increase cnt by 1 X := X + i Y := Y + j X := X / cnt Y := Y / cnt return (Y, X)
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(vector<vector<char>> matrix){ int n = matrix.size(); int m = matrix[0].size(); int cnt = 0, X = 0, Y = 0; for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++) if (matrix[i][j] == 'B') cnt++, X += i, Y += j; } X /= cnt; Y /= cnt; printf("%d, %d\n", Y, X); } int main(){ vector<vector<char>> matrix = { { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'W', 'W', 'W', 'W' }, { 'W', 'W', 'W', 'W', 'W', 'W' } }; solve(matrix); }
Input
{ { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'W', 'W', 'W', 'W' }, { 'W', 'W', 'W', 'W', 'W', 'W' } }
Output
3, 1
Advertisements
To Continue Learning Please Login
Login with Google