我正在使用双数组,这是一个任意大小的方格(3x3,4x4等)我想创建一个布尔方法,检查每行,列和对角线的总和是否相等。如果所有总和相等,则该方法返回布尔值true。 迭代网格并比较所有总和的最佳方法是什么?
//check sum of diagonal
int sum = 0;
for (int ix = 0; ix < arr.length; ++ix)
{
sum =+ arr[ix][ix];
}
//sum rows
for (int row = 0; row < arr.length; ++row)
{
for (int col = 0; col < arr[row].length; ++col)
{
sumRow =+ arr[row][col];
if(sumRow == sum)
{
for (row = 0; row < arr.length; ++row)
{
for (col = 0; col < arr[row].length; ++col)
{
sumRow =+ arr[row][col];
}
}
}
else
{
return bln;
}
}
}
if (sumRow == sum)
{
for (int col = 0; col < arr[0].length; ++col)
{
for (int row = 0; row < arr.length; ++row)
{
sumCol =+ arr[row][col];
}
}
}
if (sumRow == sum && sumCol == sum)
{
bln = true;
}
else
{
return bln;
}
return bln;
}
答案 0 :(得分:1)
我不会实现完整的解决方案,但方法vaildSquareMatrix
中的注释会使您自己的想法正确化,因为您处于正确的轨道上。
import java.util.Arrays;
class Main {
public static void main(String[] args) {
//two matrices for testing (Your can create bigger test matrices if you want)
int matrix1[][] = {{5,5,5},{5,5,5},{5,5,5}};
int matrix2[][] = {{5,4,3},{2,3,5},{3,2,4}};
System.out.println(validSquareMatrix(matrix1)); // should return true
System.out.println(validSquareMatrix(matrix2)); // should return false
}
public static boolean validSquareMatrix(int matrix[][]) {
//System.out.println(Arrays.deepToString(matrix)); // useful for debugging
int sum = 0;
//TODO: store the value for the total of the first row in sum
//TODO: check all other rows to see if the total of each row equals sum, return false if a row's total does not
//TODO: check all columns totals see if the total of each column equals sum, return false if a columns's total does not
//TODO: check both diagonals total to see if they both equal sum, return false if either diagonals total does not
//else return true
return true;
}
}