2017-03-07 55 views
-3

我正在处理任何大小的正方形网格(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; 
} 
+2

到目前为止你做了什么? – nullpointer

+0

你有这么多的3x3,4x4矩阵吗? – smttsp

+0

我知道这是不正确的,我只是不知道如何更准确地做到这一点 – shev

回答

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; 
    } 
}