You are given an m x n integer matrix mat and an integer k. The matrix rows are 0-indexed.
The following proccess happens k times:
- Even-indexed rows (0, 2, 4, ...) are cyclically shifted to the left.

- Odd-indexed rows (1, 3, 5, ...) are cyclically shifted to the right.

Return true if the final modified matrix after k steps is identical to the original matrix, and false otherwise.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4
Output: false
Explanation:
In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).

Example 2:
Input: mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2
Output: true
Explanation:

Example 3:
Input: mat = [[2,2],[2,2]], k = 3
Output: true
Explanation:
As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.
출처 : https://leetcode.com/problems/matrix-similarity-after-cyclic-shifts/description/
풀이
function areSimilar(mat: number[][], k: number): boolean {
function deepCopy(arr: number[][]) {
return arr.map((row) => row.slice());
}
let OppMat = deepCopy(mat);
for (let i = 1; i <= k; i++) {
for (let j = 0; j < OppMat.length; j++) {
if (j % 2 === 0) {
let firstItem: number = OppMat[j].shift()!; //beginning to end
OppMat[j].push(firstItem);
} else {
let lastItem: number = OppMat[j].pop()!; //end to beginning
OppMat[j].unshift(lastItem);
}
}
}
return JSON.stringify(mat) === JSON.stringify(OppMat);
};
주어진 행렬 mat가 k번의 특정한 연산 후에도 원래 행렬과 같은지 확인하는 함수
- 짝수 인덱스의 행은 왼쪽으로 한 칸씩 회전하고, 홀수 인덱스의 행은 오른쪽으로 한 칸씩 회전
- deepCopy 함수는 주어진 2차원 배열 arr의 깊은 복사본을 반환.
- arr.map((row) => row.slice())는 JavaScript에서 배열의 깊은 복사를 만드는 한 방법
- areSimilar 함수 내부에서 OppMat이라는 변수에 mat의 깊은 복사본을 저장.
- for 루프는 k번 반복.
- 내부의 for 루프는 행렬의 각 행을 순회인덱스 j가 짝수인 경우 해당 행을 왼쪽으로 한 칸 회전하고, 인덱스 j가 홀수인 경우 해당 행을 오른쪽으로 한 칸 회전
- 짝수 인덱스의 행: shift 메서드를 사용하여 첫 번째 요소를 꺼내어 행의 끝에 추가
- 홀수 인덱스의 행: pop 메서드를 사용하여 마지막 요소를 꺼내어 행의 처음에 추가
- 연산이 모두 끝난 후, 원래의 행렬 mat와 변형된 행렬 OppMat을 JSON 문자열로 변환하여 비교. 두 문자열이 같다면, true를 반환하고, 그렇지 않으면 false를 반환.
'LeetCode' 카테고리의 다른 글
| 3046. Split the Array / TypeScirpt (0) | 2024.06.15 |
|---|---|
| 1598. Crawler Log Folder / TypeScript (0) | 2024.06.15 |
| 2138. Divide a String Into Groups of Size k / TypeScript (0) | 2024.06.11 |
| 868. Binary Gap / TypeScript (0) | 2024.06.10 |
| 3033. Modify the Matrix / TypeScript (1) | 2024.06.09 |