C++ 检查相邻点的值

C++ 检查相邻点的值,c++,arrays,C++,Arrays,我目前正在编写一个代码,用于检查给定索引的邻居(北、西、东、南),如果邻居的值为0或11,则应返回false。起点为0,0,其值为4。 这是我的测试函数 bool testG(int grid[ROW][COL], int row, int col) { if (row < 0 || col < 0 || row >= ROW || col >= COL) return false; return grid[

我目前正在编写一个代码,用于检查给定索引的邻居(北、西、东、南),如果邻居的值为0或11,则应返回false。起点为0,0,其值为4。 这是我的测试函数

 bool testG(int grid[ROW][COL], int row, int col) {
         if (row < 0 || col < 0 || row >= ROW || col >= COL)
             return false;
         return grid[row][col] == 0 || grid[row][col] == 11;
    }
这是我的2d数组,如果调用函数,它应该返回false

int grid[ROW][COL] {{ 4, 11, 1, 1 },
                  { 0, 0, 1, 0 },
                  { 0, 1, 5, 0},
                  { 0, 5, 0,0 } };
如果数组看起来像这样,它应该返回true

 int grid[ROW][COL] {{ 4, 11, 1, 1 },
                      { 1, 1, 1, 0 },
                      { 0, 1, 5, 0},
                      { 0, 5, 0,0 } };
我的问题是if查询的前两部分
if(testG(grid,-1,0)和&testG(grid,0,-1)
对于上面的2d数组,这不会返回true,因为数字4的西面和北面是不允许的。 如何优化代码,使索引的一部分在超出范围时被忽略,但如果其他查询正确,则应返回false


提前感谢。

看起来您想判断每个单元格是否为以下其中一个:

  • 出界
  • 值为0
  • 有价值11
为了实现这一点,函数
testG
不仅应该为“have value 0”和“have value 11”情况返回
true
,而且还应该为“out of bounds”情况返回
true

bool-testG(int-grid[ROW][COL],int-ROW,int-COL){
如果(行<0 | |列<0 | |列>=行| |列>=列)
return true;//对于越界情况返回true
返回网格[行][col]==0 | |网格[行][col]==11;
}
结构位置{
int行=0;
int col=0;
};
int get(int grid[行][列],位置l){
返回网格[l.row][l.col];
}
std::向量get_邻接(位置l){
std::向量检索;
如果(l.row-1>=0)返回推回({l.row-1,l.col});
如果(l.row+1=0)返回推送({l.row,l.col-1});
如果(l.col+1

这试图将相邻的边界内逻辑与测试逻辑分开。

testG
返回
true
进行边界外查询如何?这是否回答了您的问题?@MikeCAT非常感谢!!
 int grid[ROW][COL] {{ 4, 11, 1, 1 },
                      { 1, 1, 1, 0 },
                      { 0, 1, 5, 0},
                      { 0, 5, 0,0 } };
bool testG(int grid[ROW][COL], int row, int col) {
    if (row < 0 || col < 0 || row >= ROW || col >= COL)
        return true; // return true for out-of-bounds case
    return grid[row][col] == 0 || grid[row][col] == 11;
}
struct location {
  int row = 0;
  int col = 0;
};
int get( int grid[ROW][COL], location l ) {
  return grid[l.row][l.col];
}
std::vector<location> get_adjacents( location l ) {
  std::vector<location> retval;
  if (l.row-1 >= 0) retval.push_back( {l.row-1, l.col} );
  if (l.row+1 < ROW) retval.push_back( {l.row+1, l.col} );
  if (l.col-1 >= 0) retval.push_back( {l.row, l.col-1} );
  if (l.col+1 < COL) retval.push_back( {l.row, l.col+1} );
  return retval;
}
bool testG_adjacents( int grid[ROW][COL], location l ) {
  for (auto adjacent : get_adjacents(l) ) 
    if (!testG(grid, adjacent.row, adjacent.col))
      return false;
  return true;
}