我正在尝试创建一个函数,该函数将检查特定元素的较大数组中的3x3数组元素块。
9...84.6.
..4..75.8
.3.......
3....1...
.7.5.6.4.
...4....2
.......5.
5.97..2..
.8.21...4
我想传入一个编号为0-8的方框,只在所选的方框内查找x。益智数组可能与上面类似。
protected static boolean box(int box, int x){
//box is a 3x3 subset of puzzle
// 012
// 345 <--- boxes numbered as such
// 678
boolean present = false;
int coordR = 0, coordC = 0;
switch (box){
case 0:
coordR = 0;
coordC = 0;
case 1:
coordR = 0;
coordC = 3;
case 2:
coordR = 0;
coordC = 6;
case 3:
coordR = 3;
coordC = 0;
case 4:
coordR = 3;
coordC = 3;
case 5:
coordR = 3;
coordC = 6;
case 6:
coordR = 6;
coordC = 0;
case 7:
coordR = 6;
coordC = 3;
case 8:
coordR = 6;
coordC = 6;
}
System.out.print("Box " + box + " -\t");
for (int i = coordR; i < 3; i++){
for (int j = coordC; j < 3; j++){
if (puzzle[i][j] == x){
present = true;
}
System.out.print(puzzle[i][j]);
}
}
System.out.println("");
return present;
}
是否有更有效的方法来实现这一目标?
答案 0 :(得分:0)
不确定
protected static boolean box(int box, int d) {
int boxY = box / 3;
int boxX = box - (boxY * 3);
int minX = boxX * 3;
int maxX = minX + 3;
int minY = boxY * 3;
int maxY = maxX + 3;
for (int y = minY; y < maxY; y++)
for (int x = minX; x < maxX; x++)
if (puzzle[x][y] == d)
return true;
return false;
}
供将来参考:你不应该忘记switch语句中的break语句。