我正在尝试计算20x20 网格中四个相邻数字(整数)中的最大乘积。
这是我目前所拥有的......
/**
* The maxProduct method is used to compute the largest product across four
* consecutive integers (either horizontally, vertically, or diagonally).
*
* @param gridData - A 20x20 array containing the integer values.
* @return maxProduct - The largest product.
*/
private static int maxProduct(int[][] gridData)
{
int maxProduct = 0;
int currentProduct = 0;
// Compute the products across the columns.
for (int row = 0; row < 20; row++)
for (int column = 0; column < 17; column++)
{
currentProduct = gridData[row][column]
* gridData[row][column + 1] * gridData[row][column + 2]
* gridData[row][column + 3];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
// Compute the products across the rows.
for (int column = 0; column < 20; column++)
for (int row = 0; row < 17; row++)
{
currentProduct = gridData[row][column]
* gridData[row + 1][column] * gridData[row + 2][column]
* gridData[row + 3][column];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
// Compute the products across the right diagonals.
for (int column = 0; column < 17; column++)
for (int row = 0; row < 17; row++)
{
currentProduct = gridData[row][column]
* gridData[row + 1][column + 1]
* gridData[row + 2][column + 2]
* gridData[row + 3][column + 3];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
// Compute the products across the left diagonals.
for (int column = 19; column < 3; column--)
for (int row = 0; row < 17; row++)
{
currentProduct = gridData[row][column]
* gridData[row + 1][column - 1]
* gridData[row + 2][column - 2]
* gridData[row + 3][column - 3];
if (currentProduct > maxProduct)
{
maxProduct = currentProduct;
}
}
return maxProduct;
}
我已经从我的另一个项目中复制了这段代码(它恰好是一个使用 8x8 网格的 Connect 4 游戏)。显然我的 Connect 4 游戏代码不起作用。我的左对角线未能通过测试用例,我很肯定我已经在这个方法中解决了这个问题。
功能应该是相同的(就计算产品而言),但我没有找到正确的值。
我的逻辑哪里错了?