[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实现

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;
}
}
posted @   CNoodle  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2022-08-29 [LeetCode] 1470. Shuffle the Array
点击右上角即可分享
微信分享提示