Pārlūkot izejas kodu

#feat:leetcode p2946题题解

yangyi 2 nedēļas atpakaļ
vecāks
revīzija
fe8cbb1457

+ 34 - 0
src/leetcode/p2946/Solution.java

@@ -0,0 +1,34 @@
+package leetcode.p2946;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/27 10:41
+ * @Description: https://leetcode.cn/problems/matrix-similarity-after-cyclic-shifts/
+ * 2946. 循环移位后的矩阵相似检查
+ */
+public class Solution {
+    public boolean areSimilar(int[][] mat, int k) {
+        /**
+         * 直接模拟,计算出移动后的值与当前值是否相等
+         * 模运算
+         */
+        int m = mat.length;
+        int n = mat[0].length;
+        for (int i = 0; i < m; i++) {
+            for (int j = 0; j < n; j++) {
+                if (i % 2 == 0){
+                    //shift left
+                    int index = (j + k) % n;
+                    if (mat[i][j] != mat[i][index])return false;
+                }else {
+                    //shift right
+                    int index = (((j - k) % n) + n) % n;
+                    if (mat[i][j] != mat[i][index])return false;
+                }
+            }
+        }
+        return true;
+    }
+}

+ 45 - 0
src/leetcode/p2946/SolutionTest.java

@@ -0,0 +1,45 @@
+package leetcode.p2946;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/27 10:49
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private final int[][] nums;
+    private final int k;
+    private final boolean expected;
+
+    public SolutionTest(int[][] nums, int k, boolean expected) {
+        this.nums = nums;
+        this.k = k;
+        this.expected = expected;
+    }
+
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {new int[][]{{1,2,1,2},{5,5,5,5},{6,3,6,3}},2,true},
+                {new int[][]{{2,2},{2,2}},3,true},
+                {new int[][]{{1,2}},1,false},
+        });
+    }
+
+    @Test
+    public void areSimilar() {
+        assertEquals(expected,solution.areSimilar(nums,k));
+    }
+}