【发布时间】:2020-04-22 01:39:53
【问题描述】:
我们有一个 m 行 n 列的矩阵,对于 m 和 n 的偶数值,我们有 4 个中心。我们需要找到最小值。将最大元素带到矩阵中心所需的交换次数。可以与水平和垂直相邻的元素进行交换。
import java.util.ArrayList;
import java.util.Scanner;
public class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int m = sc.nextInt();
int n = sc.nextInt();
int[][] arr = new int[m][n];
int max = Integer.MIN_VALUE;
ArrayList<Integer> x = new ArrayList<>();
ArrayList<Integer> y = new ArrayList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
if (arr[i][j] > max)
max = arr[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == max) {
x.add(i);
y.add(j);
}
}
}
ArrayList<Integer> centreX = new ArrayList<>();
ArrayList<Integer> centreY = new ArrayList<>();
if (m % 2 != 0 && n % 2 != 0) {
centreX.add(m / 2);
centreY.add(n / 2);
}
if (m % 2 == 0 && n % 2 == 0) {
centreX.add(m / 2);
centreY.add(n / 2);
centreX.add((m / 2) - 1);
centreY.add(n / 2);
centreX.add(m / 2);
centreY.add((n / 2) - 1);
centreX.add((n / 2) - 1);
centreY.add((m / 2) - 1);
}
if (m % 2 == 0 && n % 2 != 0) {
centreX.add(m / 2);
centreY.add(n / 2);
centreX.add((m / 2) - 1);
centreY.add(n / 2);
}
if (m % 2 != 0 && n % 2 == 0) {
centreX.add(m / 2);
centreY.add(n / 2);
centreX.add(m / 2);
centreY.add((n / 2) - 1);
}
int min_swap = Integer.MAX_VALUE;
for (int i = 0; i < x.size(); i++) {
for (int j = 0; j < centreX.size(); j++) {
int swap = Math.abs(x.get(i) - centreX.get(j)) + Math.abs(y.get(i) - centreY.get(j));
if (swap < min_swap)
min_swap = swap;
}
}
System.out.println(min_swap);
}
}
}
我正在接受输入,然后根据矩阵的维数 m 和 n 计算矩阵的中心。它通过了示例案例,但其他案例失败了。
【问题讨论】:
-
哪些案例失败了?举一个具体的例子。如果连你都不知道任何失败的例子,我们应该猜谁?
-
我添加了示例测试用例并输出为 pastebin 链接。
-
那么,哪一个失败了?你会期待什么结果?
-
@MrSmith42 测试用例被隐藏了,需要我们自己找出来。