[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:
Input: grid = [[1,0,2],[1,0,2]]
Output: true
Explanation:
All the cells in the grid satisfy the conditions.
Example 2:
Input: grid = [[1,1,1],[0,0,0]]
Output: false
Explanation:
All cells in the first row are equal.
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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2022-08-29 [LeetCode] 1470. Shuffle the Array