gpt4 book ai didi

c++ - 在 C++ 中使用二维数组

转载 作者:行者123 更新时间:2023-11-30 05:07:49 24 4
gpt4 key购买 nike

我正在处理一个包含 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;
}

我怎样才能写得更优雅,我怎样才能标记 grid[n][] 以便稍后比较它们?

例子:

if grid[1][] returns true then I need to know later to compare if grid[1][] == grid[2][] == true

最佳答案

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

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

关于c++ - 在 C++ 中使用二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47108489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com