LeetCode 题解工作台

判断矩阵是否满足条件

给你一个大小为 m x n 的二维矩阵 grid 。你需要判断每一个格子 grid[i][j] 是否满足: 如果它下面的格子存在,那么它需要等于它下面的格子,也就是 grid[i][j] == grid[i + 1][j] 。 如果它右边的格子存在,那么它需要不等于它右边的格子,也就是 grid[i…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们可以遍历每一个格子,判断其是否满足题目条件,如果有一个格子不满足条件,我们就返回 `false`,否则返回 `true`。 时间复杂度 $O(m \times n)$,其中 和 分别是矩阵 `grid` 的行数和列数。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个大小为 m x n 的二维矩阵 grid 。你需要判断每一个格子 grid[i][j] 是否满足:

  • 如果它下面的格子存在,那么它需要等于它下面的格子,也就是 grid[i][j] == grid[i + 1][j] 。
  • 如果它右边的格子存在,那么它需要不等于它右边的格子,也就是 grid[i][j] != grid[i][j + 1] 。

如果 所有 格子都满足以上条件,那么返回 true ,否则返回 false 。

 

示例 1:

输入:grid = [[1,0,2],[1,0,2]]

输出:true

解释:

网格图中所有格子都符合条件。

示例 2:

输入:grid = [[1,1,1],[0,0,0]]

输出:false

解释:

同一行中的格子值都相等。

示例 3:

输入:grid = [[1],[2],[3]]

输出:false

解释:

同一列中的格子值不相等。

 

提示:

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

解题思路

方法一:模拟

我们可以遍历每一个格子,判断其是否满足题目条件,如果有一个格子不满足条件,我们就返回 false,否则返回 true

时间复杂度 O(m×n)O(m \times n),其中 mmnn 分别是矩阵 grid 的行数和列数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an approach that involves iterating through rows and columns to check for uniformity.

  • question_mark

    Ensure the candidate efficiently handles the grid with a simple comparison for correctness.

  • question_mark

    Test whether the candidate identifies the pattern of checking rows and columns in grid validation.

warning

常见陷阱

外企场景
  • error

    Not correctly iterating through each row or column to check for uniformity.

  • error

    Misunderstanding the constraints and mistakenly returning incorrect results for non-uniform cells.

  • error

    Overcomplicating the solution by introducing unnecessary operations or data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider cases where grid elements may be different but still satisfy conditions.

  • arrow_right_alt

    Try solving the problem by verifying one condition first and then moving to the next step for optimization.

  • arrow_right_alt

    Explore optimization for larger grids when applicable by considering reduced time complexity solutions.

help

常见问题

外企场景

判断矩阵是否满足条件题解:数组·matrix | LeetCode #3142 简单