iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0
自我挑戰組

Leetcode 解題之旅:逐日攻克系列 第 11

每日一LeetCode(11)

  • 分享至 

  • xImage
  •  

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:

https://ithelp.ithome.com.tw/upload/images/20240512/20162696RoRU5ag0vH.jpg
All the cells in the grid satisfy the conditions.

Example 2:

Input: grid = [[1,1,1],[0,0,0]]

Output: false

Explanation:

https://ithelp.ithome.com.tw/upload/images/20240512/201626962xPbxYYfv9.jpg
All cells in the first row are equal.

Example 3:

Input: grid = [[1],[2],[3]]

Output: false

Explanation:
https://ithelp.ithome.com.tw/upload/images/20240512/20162696t1vA6Pd1Gz.jpg
Cells in the first column have different values.

class Solution {
public:
    bool satisfiesConditions(vector<vector<int>>& grid) {
        int n = grid.size();
        int m = grid[0].size();
        for(int i=0; i+1<n; ++i)
        {
            for(int j=0; j<m; ++j)
            {
                if(grid[i][j] != grid[i+1][j])
                {
                    return false;
                }
            }
        }
        for(int i=0; i<n; ++i)
        {
            for(int j=0; j+1<m; ++j)
            {
                if(grid[i][j]==grid[i][j+1])
                {
                    return false;
                }
            }
        }
        return true;
    }
};

上一篇
每日一LeetCode(10)
下一篇
每日一LeetCode(12)
系列文
Leetcode 解題之旅:逐日攻克30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言