[LeetCode] Matrix Similarity After Cyclic Shifts

2946. Matrix Similarity After Cyclic Shifts

You are given a 0-indexed m x n integer matrix mat and an integer k. You have to cyclically right shift odd indexed rows k times and cyclically left shift even indexed rows k times.

Return true if the initial and final matrix are exactly the same and false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
bool areSimilar(vector<vector<int>>& mat, int k) {
int p = 0;
for(auto& r : mat) {
deque<int> dq;
for(int i = 0; i < r.size(); i++) dq.push_back(r[i]);
int mv = k % r.size();
if(p % 2 == 0) {
while(mv--) {
dq.push_back(dq.front()); dq.pop_front();
}
} else {
while(mv--) {
dq.push_front(dq.back()); dq.pop_back();
}
}

for(int i = 0; i < dq.size(); i++) {
if(dq[i] != r[i]) return false;
}
p += 1;
}


return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/26/PS/LeetCode/matrix-similarity-after-cyclic-shifts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.