我有一个5x6矩阵,我使用Java Swing中的单个按钮创建。
我将它们命名为棋盘,从左上角到右下角为A1到F5。
现在,我想让用户只能水平或垂直点击给定数量的相邻按钮。
说,值为4.因此,用户必须能够在矩阵中的任何位置选择仅垂直或水平相邻的4个按钮。
例如。 D2,C2,B2,A2如果垂直选择。 或者,如果水平选择,可能是D1,D2,D3,D4。
为矩阵中的任何按钮设置实现此功能的算法是什么?
答案 0 :(得分:1)
这里是代码,我添加了一些评论以使其更清晰。
请注意,代码中的数组应排序
<强>逻辑强>
水平
A1 => 01
A2 => 02
A3 => 03
A4 => 04
So A2 - A1 = 1
垂直
A1 => 01
B1 => 11
C1 => 21
D1 => 31
So B1 - A1 = 10
<强>代码:强>
public static void main(String[] args) {
String[] spots0 = { "A1", "B1", "C1", "D1" };
String[] spots1 = { "A1", "A2", "A3", "A4" };
String[] spots2 = { "A1", "B1", "B2", "B3" };
System.out.println(isCorrect(spots0) ? "correct" : "incorrect");
System.out.println(isCorrect(spots1) ? "correct" : "incorrect");
System.out.println(isCorrect(spots2) ? "correct" : "incorrect");
}
public static boolean isCorrect(String[] spots) {
int NONE = -1;
int HORIZONTAL = 1;
int VERTICAL = 2;
int pattern = NONE; //BY DEFAULT NONE
for (int i = 0; i < spots.length - 1; i++) {
//difference between 2 consecutive element in spots[]. If A2 - A1 = 1, and B1 - A1 = 10
int diff = toNum(spots[i + 1]) - toNum(spots[i]);
if (diff == 1) { // if HORIZONTAL
if (pattern == NONE) // if the first time
pattern = HORIZONTAL; // set pattern to vertical, this is used for later to check if any illigal change happen
else if (pattern == VERTICAL) { //if it was Vertical and changed, then error
return false;
}
} else if (diff == 10) { // if VERTICAL
if (pattern == NONE) // if the first time
pattern = VERTICAL; // set pattern to horizontal, this is used for later to check if any illigal change happen
else if (pattern == HORIZONTAL) { //if it was Horizontal and changed, then error
return false;
}
} else {
return false;
}
}
return true;
}
public static int toNum(String s) {
// A1 => 01 , B1 => 11, C2 => 22
return Integer.parseInt("" + ((int)s.charAt(0) - 'A') + s.charAt(1));
}