
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Check If Given Flag Is Stripped or Not in C++
Suppose we have a matrix of size n x m. Each cell will hold one value from 0 to 9. There is a flag should be striped: each horizontal row of the flag should contain squares of the same color, and the colors of the adjacent horizontal rows should be different. We have to check given matrix is valid flag or not.
So, if the input is like
0 | 0 | 0 |
1 | 1 | 1 |
3 | 3 | 3 |
Steps
To solve this, we will follow these steps −
n := row count of matrix m := column count of matrix l := 'm' res := 1 for initialize i := 0, when i < n, update (increase i by 1), do: f := matrix[i, 0] for initialize j := 0, when j < m, update (increase j by 1), do: if matrix[i, j] is not equal to f, then: res := 0 if l is same as f, then: res := 0 l := f return (if res is non-zero, then true, otherwise false)
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(vector<vector<int>> matrix){ int n = matrix.size(); int m = matrix[0].size(); char l = 'm'; bool res = 1; for (int i = 0; i < n; i++){ char f = matrix[i][0]; for (int j = 0; j < m; j++){ if (matrix[i][j] != f) res = 0; } if (l == f) res = 0; l = f; } return res ? true : false; } int main(){ vector<vector<int>> matrix = { { 0, 0, 0 }, { 1, 1, 1 }, { 3, 3, 3 } }; cout << solve(matrix) << endl; }
Input
{ { 0, 0, 0 }, { 1, 1, 1 }, { 3, 3, 3 } }
Output
1
Advertisements