Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

주어진 플래그가 제거되었는지 확인하는 C++ 코드

<시간/>

크기가 n x m인 행렬이 있다고 가정합니다. 각 셀은 0에서 9까지 하나의 값을 보유합니다. 줄무늬가 있어야 하는 플래그가 있습니다. 플래그의 각 수평 행에는 동일한 색상의 사각형이 포함되어야 하고 인접한 수평 행의 색상은 달라야 합니다. 주어진 행렬이 유효한 플래그인지 확인해야 합니다.

따라서 입력이 다음과 같으면

0 0 0
1 1 1
3 3 3

단계

이 문제를 해결하기 위해 다음 단계를 따릅니다. −

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)

예시

이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

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

입력

{ { 0, 0, 0 }, { 1, 1, 1 }, { 3, 3, 3 } }

출력

1