comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
Easy |
1303 |
Biweekly Contest 130 Q1 |
|
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:
Input: grid = [[1,0,2],[1,0,2]]
Output: true
Explanation:
All the cells in the grid satisfy the conditions.
Example 2:
Example 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
We can iterate through each cell and determine whether it meets the conditions specified in the problem. If there is a cell that does not meet the conditions, we return false
, otherwise, we return true
.
The time complexity is grid
respectively. The space complexity is $O(1)`.
class Solution:
def satisfiesConditions(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
if i + 1 < m and x != grid[i + 1][j]:
return False
if j + 1 < n and x == grid[i][j + 1]:
return False
return True
class Solution {
public boolean satisfiesConditions(int[][] grid) {
int m = grid.length, n = grid[0].length;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] != grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
}
class Solution {
public:
bool satisfiesConditions(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] != grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
};
func satisfiesConditions(grid [][]int) bool {
m, n := len(grid), len(grid[0])
for i, row := range grid {
for j, x := range row {
if i+1 < m && x != grid[i+1][j] {
return false
}
if j+1 < n && x == grid[i][j+1] {
return false
}
}
}
return true
}
function satisfiesConditions(grid: number[][]): boolean {
const [m, n] = [grid.length, grid[0].length];
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (i + 1 < m && grid[i][j] !== grid[i + 1][j]) {
return false;
}
if (j + 1 < n && grid[i][j] === grid[i][j + 1]) {
return false;
}
}
}
return true;
}