我正在尝试为我的战舰程序创建一个函数,以创建一个概率网格,其中包含任何剩余部分可能位于的所有位置。我希望网格遍历整个数组,然后检查是否在那个位置点对象有空间放置(水平或垂直)并在它将覆盖的每个点上加一个,向我显示哪个坐标最有可能在其上放置一艘船。 BS_GRID_ROWS 和 BS_GRID_COLS 这两个值都保存了战舰板的大小,矩阵是我想显示我的概率值的数组,而 hits 是一个数组,如果一艘船被击中,它的数字(对应于每艘船)大于零,- 1 如果我射门但没打中,如果在那个坐标没有射门则为零。这是我到目前为止的代码。它正在工作但不正确,它完全错过了最后的几个方 block ,我知道在放置任何船只之前运行它时我知道这是不可能的。任何帮助,将不胜感激。谢谢
void
probabilityGrid(int matrix[BS_GRID_ROWS][BS_GRID_COLS], int hits[BS_GRID_ROWS][BS_GRID_COLS], int shipSize)
{
bool isValid=true;
for (int row = 0; row< BS_GRID_ROWS; row++)
{
for (int col = 0; (col+shipSize) <BS_GRID_COLS; col++)
{
for (int hold = col; hold < shipSize; hold++)
{
if (hits[row][hold]!=0)
isValid=false;
}
if (isValid)
{
for (int hold = col; hold < shipSize; hold++)
{
matrix[row][hold]++;
}
}
isValid=true;
}
}
//For now I'm just working on the horizontal part of the algorithm.
}
最佳答案
想象一下(或更好地设置并通过调试器运行)BS_GRID_ROWS == 1
, BS_GRID_COLS == 1
, 和 shipSize == 1
.
发生的情况是条件 (col+shipSize) <BS_GRID_COLS
是false
即使col == 0
这可能不是您想要的,您应该将其更改为 col + shipSize <= BS_GRID_COLS
.
出于同样的原因,你应该改变row<=BS_GRID_ROWS-shipSize-1
至 row + shipSize <= BS_GRID_ROWS
.
关于c++ - 战舰概率网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834879/