[LeetCode] 3142. Check if Grid Satisfies Conditions

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:
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 2
Input: grid = [[1,1,1],[0,0,0]]
Output: false

Explanation:
All cells in the first row are equal.

Example 3:
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

判断矩阵是否满足条件。

给你一个大小为 m x n 的二维矩阵 grid 。你需要判断每一个格子 grid[i][j] 是否满足: 如果它下面的格子存在,那么它需要等于它下面的格子,也就是 grid[i][j] == grid[i + 1][j] 。 如果它右边的格子存在,那么它需要不等于它右边的格子,也就是 grid[i][j] != grid[i][j + 1] 。 如果 所有 格子都满足以上条件,那么返回 true ,否则返回 false 。

思路

这道题不涉及算法,就是矩阵的遍历。

复杂度

时间O(mn)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public boolean satisfiesConditions(int[][] grid) {
int m = grid.length;
int n = grid[0].length;

// grid[i][j] == grid[i + 1][j]
for (int i = 0; i < m - 1; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != grid[i + 1][j]) {
return false;
}
}
}

// grid[i][j] != grid[i][j + 1]
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - 1; j++) {
if (grid[i][j] == grid[i][j + 1]) {
return false;
}
}
}
return true;
}
}

[LeetCode] 3142. Check if Grid Satisfies Conditions
https://shurui91.github.io/posts/135857717.html
Author
Aaron Liu
Posted on
August 28, 2024
Licensed under