3142. Check if Grid Satisfies Conditions

3142. Check if Grid Satisfies Conditions

Description

You are given a 2D matrix grid of size m x n. You need to check if each cell grid[i][j] is:

  • Equal to the cell below it, i.e. grid[i][j] == grid[i + 1][j] (if it exists).
  • Different from the cell to its right, i.e. grid[i][j] != grid[i][j + 1] (if it exists).

Return true if all the cells satisfy these conditions, otherwise, return false.

Example 1:

1
2
3
Input: grid = [[1,0,2],[1,0,2]]

Output: true

Explanation:

All the cells in the grid satisfy the conditions.

Example 2:

1
2
3
Input: grid = [[1,1,1],[0,0,0]]

Output: false

Explanation:

All cells in the first row are equal.

Example 3:

1
2
3
Input: grid = [[1],[2],[3]]

Output: false

Explanation:

Cells in the first column have different values.

Constraints:

  • 1 <= n, m <= 10
  • 0 <= grid[i][j] <= 9

Hints/Notes

  • N/A

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool satisfiesConditions(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int j = 0; j < n; j++) {
for (int i = 0; i < m - 1; i++) {
if (grid[i][j] != grid[i + 1][j]) {
return false;
}
}
if (j > 0 && grid[0][j] == grid[0][j - 1]) {
return false;
}
}
return true;
}
};