如果已知矩阵的内容仅包含维度rows x cols 内的范围[min..max) 中的数字,则最好检查start 和destination 是否都属于此范围以及它们必须不同(自相邻被忽略)。
使用start 值可以计算row 和col 值。
最后检查目的地是否在相邻的单元格中。
注意:如果start 和destination 相邻,则该方法应返回布尔值true,否则返回false。
// default matrix 3x3, starting from 0
public static boolean check(int start, int destination) {
return check(start, destination, 3);
}
// square matrix n x n, starting from 0
public static boolean check(int start, int destination, int n) {
return check(start, destination, 0, n, n);
}
// rectangular matrix rows x cols, starting from 0
public static boolean check(int start, int destination, int rows, int cols) {
return check(start, destination, 0, rows, cols);
}
// rectangular matrix rows x cols, starting from min
public static boolean check(int start, int destination, int min, int rows, int cols) {
int max = min + rows * cols - 1;
if (start < min || start > max || destination < min || destination > max || start == destination) {
return false;
}
int rs = (start - min) / cols;
int cs = (start - min) % cols;
int rd = (destination - min) / cols;
int cd = (destination - min) % cols;
return ((rs == rd + 1 || rd == rs + 1) && (cs == cd))
|| ((cs == cd + 1 || cd == cs + 1) && (rs == rd));
}
测试(打印矩阵和邻接图):
public static void matrix(int min, int rows, int cols) {
System.out.print(" | ");
for (int i = 0; i < cols; i++) {
System.out.printf("%2d ", i);
}
System.out.println("\n" + "=".repeat(1 + cols * 4));
int max = min + rows * cols;
for (int i = 0; i < rows; i++) {
System.out.print(i + "| ");
for (int j = 0; j < cols; j++) {
System.out.printf("%2d ", min + cols * i + j);
}
System.out.println();
}
}
public static void adjacency(int min, int rows, int cols) {
int max = min + rows * cols;
System.out.printf("Range: [ %2d, %2d)%n", min, max);
System.out.print(" | ");
for (int i = min; i < max; i++) {
System.out.printf("%2d ", i);
}
System.out.println("\n" + "=".repeat(4 + rows * cols * 4));
for (int i = min; i < max; i++) {
System.out.printf("%2d| ", i);
for (int j = min; j < max; j++) {
System.out.printf("%2s ", check(i, j, min, rows, cols) ? "Y": ".");
}
System.out.println();
}
}
测试:
int min = -4, rows = 3, cols = 4;
matrix(min, rows, cols);
adjacency(min, rows, cols);
输出:
| 0 1 2 3
=================
0| -4 -3 -2 -1
1| 0 1 2 3
2| 4 5 6 7
Range: [ -4, 8)
| -4 -3 -2 -1 0 1 2 3 4 5 6 7
====================================================
-4| . Y . . Y . . . . . . .
-3| Y . Y . . Y . . . . . .
-2| . Y . Y . . Y . . . . .
-1| . . Y . . . . Y . . . .
0| Y . . . . Y . . Y . . .
1| . Y . . Y . Y . . Y . .
2| . . Y . . Y . Y . . Y .
3| . . . Y . . Y . . . . Y
4| . . . . Y . . . . Y . .
5| . . . . . Y . . Y . Y .
6| . . . . . . Y . . Y . Y
7| . . . . . . . Y . . Y .
对于 min = 0,rows = 3,cols = 3:
Range: [ 0, 9)
| 0 1 2 3 4 5 6 7 8
========================================
0| . Y . Y . . . . .
1| Y . Y . Y . . . .
2| . Y . . . Y . . .
3| Y . . . Y . Y . .
4| . Y . Y . Y . Y .
5| . . Y . Y . . . Y
6| . . . Y . . . Y .
7| . . . . Y . Y . Y
8| . . . . . Y . Y .