Problem Description
You are given an m x n 2D matrix named grid. For each cell grid[i][j], you need to check two conditions:
- If a cell directly below exists (i.e. grid[i+1][j]), then it must be equal to grid[i][j].
- If a cell to the right exists (i.e. grid[i][j+1]), then it must be different from grid[i][j]. Return true if all cells satisfy these conditions; otherwise, return false.
Key Insights
- Iterate through every cell of the grid.
- For each cell, check the cell below (if it exists) to ensure equality.
- Check the cell to the right (if it exists) to ensure inequality.
- Early exit from the loop if any condition fails.
- The grid size is small (max 10 x 10), so a straightforward nested iteration is efficient.
Space and Time Complexity
Time Complexity: O(m * n), where m and n are the dimensions of the grid. Space Complexity: O(1), as only constant extra space is used.
Solution
We use a simple brute-force approach by iterating through each cell of the grid with nested loops. At each cell, we check:
- If the cell below exists and whether it is equal to the current cell.
- If the cell to the right exists and whether it is different than the current cell. If any cell does not meet its respective condition, we return false immediately. If all cells meet the required conditions, we return true at the end. The solution leverages simple iteration and conditional checks, ensuring clarity and efficiency given the small input size.