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.
요즘 리트코드로 코테를 풀어보고 있는데 영어로 읽다보니 자꾸 조건을 잘못 이해하고 푸는 경우가 많다😭😭
이 문제에서는 두 조건이 있다.
1) 현재 행에 있는 값과 그 다음 행에 있는 값이 같은지 확인
2) 현재 열에 있는 값과 그 다음 열에 있는 값이 다른지 확인
추가적으로 배열의 범위를 벗어나지 않는지도 같이 확인해줘야 한다!
class Solution {
public boolean satisfiesConditions(int[][] grid) {
int m = grid.length; // 행
int n = grid[0].length; // 열
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i + 1 < m && grid[i][j] != grid[i+1][j])
return false;
if (j + 1 < n && grid[i][j] == grid[i][j+1])
return false;
}
}
return true;
}
}
i + 1 < m
과 j + 1 < n
로 배열 밖에 벗어나지 않는지 확인해야 함. (i < m 해서 ArrayIndexOutOfBoundsException 떴었음)