100299. 判断矩阵是否满足条件
给你一个大小为 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
原站题解
javascript 解法, 执行用时: 71 ms, 内存消耗: 51.6 MB, 提交时间: 2024-08-29 10:50:01
/** * @param {number[][]} grid * @return {boolean} */ var satisfiesConditions = function(grid) { for (let i = 0; i < grid.length; ++i) { for (let j = 0; j < grid[0].length; ++j) { if (i + 1 < grid.length && grid[i][j] !== grid[i + 1][j]) { return false; } if (j + 1 < grid[0].length && grid[i][j] === grid[i][j + 1]) { return false; } } } return true; };
rust 解法, 执行用时: 0 ms, 内存消耗: 2 MB, 提交时间: 2024-08-29 10:49:47
impl Solution { pub fn satisfies_conditions(grid: Vec<Vec<i32>>) -> bool { for i in 0..grid.len() { for j in 0..grid[0].len() { if i + 1 < grid.len() && grid[i][j] != grid[i + 1][j] { return false; } if j + 1 < grid[0].len() && grid[i][j] == grid[i][j + 1] { return false; } } } true } }
php 解法, 执行用时: 23 ms, 内存消耗: 19.8 MB, 提交时间: 2024-05-13 14:13:50
class Solution { /** * @param Integer[][] $grid * @return Boolean */ function satisfiesConditions($grid) { foreach ( $grid as $i => $row ) { foreach ( $row as $j => $x ) { if ( $j > 0 && $grid[$i][$j] == $grid[$i][$j - 1] || $i > 0 && $grid[$i][$j] != $grid[$i - 1][$j] ) return false; } } return true; } }
golang 解法, 执行用时: 3 ms, 内存消耗: 3.6 MB, 提交时间: 2024-05-13 14:11:30
func satisfiesConditions(grid [][]int) bool { for i, row := range grid { for j, x := range row { if j > 0 && x == row[j-1] || i > 0 && x != grid[i-1][j] { return false } } } return true }
java 解法, 执行用时: 0 ms, 内存消耗: 43.2 MB, 提交时间: 2024-05-13 14:11:20
class Solution { public boolean satisfiesConditions(int[][] grid) { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (j > 0 && grid[i][j] == grid[i][j - 1] || i > 0 && grid[i][j] != grid[i - 1][j]) { return false; } } } return true; } }
cpp 解法, 执行用时: 9 ms, 内存消耗: 28 MB, 提交时间: 2024-05-13 14:11:10
class Solution { public: bool satisfiesConditions(vector<vector<int>>& grid) { for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[i].size(); j++) { if (j && grid[i][j] == grid[i][j - 1] || i && grid[i][j] != grid[i - 1][j]) { return false; } } } return true; } };
python3 解法, 执行用时: 46 ms, 内存消耗: 16.3 MB, 提交时间: 2024-05-13 14:10:59
class Solution: def satisfiesConditions(self, grid: List[List[int]]) -> bool: for i, row in enumerate(grid): for j, x in enumerate(row): if j and x == row[j - 1] or i and x != grid[i - 1][j]: return False return True