Leetcode 3142. Check if Grid Satisfies Conditions
You are given a 2D grid grid
of size m x n
containing integers. You need to check whether the grid satisfies the following conditions:
Return true
if the grid satisfies both conditions, and false
otherwise.
m
and n
) and the values within the grid?
0 x 0
, 1 x n
, and m x 1
.Here is the C++ implementation to solve the problem:
#include <vector>
bool checkGridConditions(const std::vector<std::vector<int>>& grid) {
int m = grid.size();
if (m == 0) return true; // An empty grid trivially satisfies the conditions
int n = grid[0].size();
if (n == 0) return true; // An empty grid trivially satisfies the conditions
// Check strictly increasing rows
for (int i = 0; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (grid[i][j] <= grid[i][j-1]) {
return false;
}
}
}
// Check strictly increasing columns
for (int j = 0; j < n; ++j) {
for (int i = 1; i < m; ++i) {
if (grid[i][j] <= grid[i-1][j]) {
return false;
}
}
}
return true;
}
O(m * n)
, where m
is the number of rows and n
is the number of columns.O(m * n)
.O(m * n)
.This solution iterates through each element of the grid a constant number of times, making it efficient and appropriate even for larger grids within typical competitive programming constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?