C++ code to check given flag is stripped or not


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

000
111
333

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

Updated on: 29-Mar-2022

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements