(更新) 我很難找出在這裏做什麼,我需要比較一個2d數組,以查看是否有任何數字匹配。我需要四個數字來匹配上/下,左/右或對角線。我只是無法得到它來測試下/左斜線(/)這是我更新的代碼java 2d數組比較UPDATED
public static boolean isAdjacentFour(int[][] a) {
// Code to test if column has four adjacent numbers
for (int row = 0; row <= a.length - 3 ; row++) {
for (int col = 0; col <= a[0].length - 1 ; col++) {
if (a[row][col] == a[row+1][col] && a[row+2][col] == a[row][col]
&& a[row+3][col] == a[row][col]) {
return true;
}
}
}
// Code to test if row has four adjacent numbers
for (int row = 0; row <= a.length - 1 ; row++) {
for (int col = 0; col <= a[0].length - 3 ; col++) {
if (a[row][col] == a[row][col+1] && a[row][col] == a[row][col+2]
&& a[row][col] == a[row][col+3]) {
return true;
}
}
}
// Code to test if there are 4 adjacent numbers in a down/right (\)diagonal
for (int row = 0; row <= a.length - 3 ; row++) {
for (int col = 0; col <= a[0].length - 3 ; col++) {
if (a[row][col] == a[row+1][col+1] && a[row][col] == a[row+2][col+2]
&& a[row][col] == a[row+3][col+3]) {
return true;
}
}
}
for (int row = 0; row <= a.length - 3 ; row++) {
for (int col = 0; col <= a[0].length + 3 ; col--) {
if (a[row][col] == a[row+1][col-1] && a[row][col] == a[row+2][col-2]
&& a[row][col] == a[row+3][col-3]) {
return true;
}
}
}
return false;
}
'[row + 2]'和'[row + 3]'是錯誤的原因,設置循環條件爲'row
11thdimension
上面的評論是正確的,除了我的答案我做了行<= a.length - 4來解決它,但都是可以接受的。 –