[LeetCode] 3142. Check if Grid Satisfies Conditions

CNoodle發表於2024-08-29

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;
    }
}

相關文章