在C ++中使用二维数组

时间:2017-11-04 07:24:42

标签: c++ arrays

我正在使用带有9和9个元素的二维数组,grid [9] [9],我需要检查特定元素是否相等,如果是,则标记第二个数组的第一个数组

bool gridWon(int n){
    if ( grid[n][0] != 0 && grid[n][0] == grid[n][1] && grid[n][0] == grid[n][2]){
        return true;
    } else if ( grid[n][3] != 0 && grid[n][3] == grid[n][4] && grid[n][5] == grid[n][3]){
        return true;
    } else if ( grid[n][6] != 0 && grid[n][6] == grid[n][7] && grid[n][8] == grid[n][6]){
        return true;
    } else if ( grid[n][0] != 0 && grid[n][0] == grid[n][4] && grid[n][8] == grid[n][0]){
        return true;
    } else if ( grid[n][2] != 0 && grid[n][2] == grid[n][4] && grid[n][6] == grid[n][2]){
        return true;
    } else if ( grid[n][0] != 0 && grid[n][0] == grid[n][3] && grid[n][6] == grid[n][0]){
        return true;
    } else if ( grid[n][1] != 0 && grid[n][1] == grid[n][4] && grid[n][7] == grid[n][1]){
        return true;
    } else if ( grid[n][2] != 0 && grid[n][2] == grid[n][5] && grid[n][8] == grid[n][2]){
        return true;
    } else
        return false;
}

我怎样才能写得更优雅?如何标记网格[n] []以便稍后进行比较?

示例:

  

如果grid [1] []返回true,那么我需要稍后知道比较grid [1] [] == grid [2] [] == true

1 个答案:

答案 0 :(得分:1)

返回逻辑运算的结果会更好:

bool gridWon(int n){
 return (grid[n][0] != 0 && grid[n][0] == grid[n][1] && grid[n][0] == grid[n][2]) ||
  (grid[n][3] != 0 && grid[n][3] == grid[n][4] && grid[n][5] == grid[n][3]) ||
  (grid[n][6] != 0 && grid[n][6] == grid[n][7] && grid[n][8] == grid[n][6]) ||
  (grid[n][0] != 0 && grid[n][0] == grid[n][4] && grid[n][8] == grid[n][0]) ||
  (grid[n][2] != 0 && grid[n][2] == grid[n][4] && grid[n][6] == grid[n][2]) ||
  (grid[n][0] != 0 && grid[n][0] == grid[n][3] && grid[n][6] == grid[n][0]) ||
  (grid[n][1] != 0 && grid[n][1] == grid[n][4] && grid[n][7] == grid[n][1]) ||
  (grid[n][2] != 0 && grid[n][2] == grid[n][5] && grid[n][8] == grid[n][2]);
}