阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述:
给你两个大小为 n x n 的二进制矩阵 mat 和 target 。现以 90 度顺时针轮转矩阵 mat 中的元素若干次,如果能够使 mat 与 target 一致,返回 true ;否则,返回 false 。
示例:
输入:mat = [[0,1],[1,0]], target = [[1,0],[0,1]] 输出:true 解释: mat 顺时针轮转 90 度后: 原矩阵 [[0,1],[1,0]] → 旋转90度后 [[1,0],[0,1]],与 target 一致,因此返回 true。
补充说明:
class lc3600_lc3699.lc3660.Solution {
public static boolean same(int[][] mat, int[][] target, int a, int b) {
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
if (mat[i][j] != target[i][j]) {
return false;
}
}
}
return true;
}
public static int[][] switchroom(int[][] mat) {
int n = mat.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = mat[i][j];
mat[i][j] = mat[i][n - 1 - j];
mat[i][n - 1 - j] = temp;
}
}
return mat;
}
public boolean findRotation(int[][] mat, int[][] target) {
int a = mat.length;
int b = mat[0].length;
int c = target.length;
int d = target[0].length;
if (a != c || b != d) {
return false;
}
if (same(mat, target, a, b)) {
return true;
}
switchroom(mat);
if (same(mat, target, a, b)) {
return true;
}
switchroom(mat);
if (same(mat, target, a, b)) {
return true;
}
switchroom(mat);
if (same(mat, target, a, b)) {
return true;
}
return false;
}
}原代码直接修改输入的mat矩阵,可能对外部使用造成影响,优化为复制矩阵后旋转:
public boolean findRotation(int[][] mat, int[][] target) {
int n = mat.length;
// 复制原矩阵,避免修改输入
int[][] copy = new int[n][n];
for (int i = 0; i < n; i++) {
System.arraycopy(mat[i], 0, copy[i], 0, n);
}
// 检查4种旋转状态
for (int i = 0; i < 4; i++) {
if (same(copy, target, n, n)) {
return true;
}
copy = switchroom(copy);
}
return false;
}将旋转逻辑封装为更清晰的方法,提升可读性:
private int[][] rotate90(int[][] matrix) {
int n = matrix.length;
int[][] res = new int[n][n];
// 直接计算旋转后位置,无需转置+反转(更直观)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
res[j][n - 1 - i] = matrix[i][j];
}
}
return res;
}原代码重复调用switchroom和same,优化为循环遍历4次,匹配后立即返回:
public boolean findRotation(int[][] mat, int[][] target) {
int n = mat.length;
if (n != target.length || n != target[0].length) return false;
int[][] curr = mat;
for (int i = 0; i < 4; i++) {
if (same(curr, target, n, n)) return true;
curr = switchroom(curr);
}
return false;
}时间复杂度:(O(n^2))
空间复杂度:
res[j][n-1-i] = matrix[i][j];