效果(先看单元测试效果)
代码
import org.junit.Test;
public class NineSquares {
@Test
public void nineSquaresCheckUnitTest() {
int[][] data = {
{1, 2, 3, 4, 5, 6, 7, 8, 9},
{4, 5, 6, 7, 8, 9, 1, 2, 3},
{7, 8, 9, 1, 2, 3, 4, 5, 6},
{2, 3, 1, 5, 6, 4, 8, 9, 7},
{5, 6, 4, 8, 9, 7, 2, 3, 1},
{8, 9, 7, 2, 3, 1, 5, 6, 4},
{3, 1, 2, 6, 4, 5, 9, 7, 8},
{6, 4, 5, 9, 7, 8, 3, 1, 2},
{9, 7, 8, 3, 1, 2, 6, 4, 5},
};
long s = System.currentTimeMillis();
System.out.println("校验结果:" + nineSquaresCheck(data));
System.out.println("执行时间:" + (System.currentTimeMillis() - s) + "ms");
}
private static final int[][] boxIndex = new int[][]{{1, 1}, {1, 4}, {1, 7}, {4, 1}, {4, 4}, {4, 7}, {7, 1}, {7, 4}, {7, 7}};
public boolean nineSquaresCheck(int[][] data) {
int ylen = data.length;
int xlen = data[0].length;
if (ylen != 9 || xlen != 9) {
return false;
}
for (int i = 0; i < 9; i++) {
if (!checkUnitA(data[i])) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if (!checkUnitB(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4], data[i][5], data[i][6], data[i][7], data[i][8])) {
return false;
}
}
return checkBox(data);
}
private boolean checkBox(int[][] data) {
for (int i = 0; i < boxIndex.length; i++) {
int[] boxIndexItem = NineSquares.boxIndex[i];
int y = boxIndexItem[0];
int x = boxIndexItem[1];
if (!checkUnitB(data[y - 1][x - 1], data[y - 1][x], data[y - 1][x + 1], data[y][x - 1], data[y][x], data[y][x + 1], data[y + 1][x - 1], data[y + 1][x], data[y + 1][x + 1])) {
return false;
}
}
return true;
}
private boolean checkUnitA(int[] unitData) {
int[] checks = new int[9];
for (int item : unitData) {
if (item > 9 || item < 0) {
return false;
}
int check = checks[item - 1];
if (check == 1) {
return false;
} else {
checks[item - 1] = 1;
}
}
return true;
}
private boolean checkUnitB(int... unitData) {
int[] checks = new int[9];
for (int item : unitData) {
if (item > 9 || item < 0) {
return false;
}
int check = checks[item - 1];
if (check == 1) {
return false;
} else {
checks[item - 1] = 1;
}
}
return true;
}
}
思路
思路很简单,就是常规的横轴竖轴以及每个3*3小块的校验,因为想了很多情况下,尽量减少复杂度上来说,最少27次才能全部校验完,而且我们也无法获知填写的哪一个步骤出错,所以理论没办法优化了。 校验其9个单元数据是否正确性的时候,用了数组来校验的,其他的就比较普通了。不合理的地方望指出,谢谢
|