Input: mat =[[1,2,3],[4,5,6],[7,8,9]], k =4Output: falseExplanation:
In each step left shift is applied to rows 0 and 2(even indices), and right
shift to row 1(odd index).
Input: mat =[[2,2],[2,2]], k =3Output: trueExplanation:
As all the values are equal in the matrix, even after performing cyclic shifts
the matrix will remain the same.
Each row is shifted left or right cyclically, depending on its index parity, for k times. After all shifts, we compare the resulting matrix to the original. Since shifting by the row length is a full cycle, we use modulo to optimize the number of shifts.
classSolution {
public:bool areSimilar(vector<vector<int>>& mat, int k) {
int m = mat.size(), n = mat[0].size();
for (int i =0; i < m; ++i) {
vector<int> row(n);
for (int j =0; j < n; ++j) {
int idx = (i %2==0) ? (j + k) % n : (j - k + n) % n;
row[j] = mat[i][idx];
}
if (row != mat[i]) return false;
}
return true;
}
};
classSolution {
publicbooleanareSimilar(int[][] mat, int k) {
int m = mat.length, n = mat[0].length;
for (int i = 0; i < m; i++) {
int[] row =newint[n];
for (int j = 0; j < n; j++) {
int idx = (i % 2 == 0) ? (j + k) % n : (j - k + n) % n;
row[j]= mat[i][idx];
}
for (int j = 0; j < n; j++) {
if (row[j]!= mat[i][j]) returnfalse;
}
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funareSimilar(mat: Array<IntArray>, k: Int): Boolean {
val m = mat.size
val n = mat[0].size
for (i in0 until m) {
val row = IntArray(n)
for (j in0 until n) {
val idx = if (i % 2==0) (j + k) % n else (j - k + n) % n
row[j] = mat[i][idx]
}
if (!row.contentEquals(mat[i])) returnfalse }
returntrue }
}
1
2
3
4
5
6
7
8
classSolution:
defareSimilar(self, mat: list[list[int]], k: int) -> bool:
m, n = len(mat), len(mat[0])
for i in range(m):
row = [(mat[i][(j + k) % n] if i %2==0else mat[i][(j - k) % n]) for j in range(n)]
if row != mat[i]:
returnFalsereturnTrue
impl Solution {
pubfnare_similar(mat: Vec<Vec<i32>>, k: i32) -> bool {
let m = mat.len();
let n = mat[0].len();
for i in0..m {
letmut row =vec![0; n];
for j in0..n {
let idx =if i %2==0 {
(j + k asusize) % n
} else {
(j + n - (k asusize% n)) % n
};
row[j] = mat[i][idx];
}
if row != mat[i] {
returnfalse;
}
}
true }
}