【问题标题】:checking the values of the neighboring points检查相邻点的值
【发布时间】:2021-04-05 08:16:59
【问题描述】:

我目前正在编写一个代码来检查给出的索引邻居(北、西、东、南),如果邻居的值为 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;
    }

这是我的查询:

if(testG(grid,-1,0) && testG(grid,0,-1) && testG(grid,1,0) && testG(grid,0,1)) 
{ 
  return false;
}

这是我的二维数组,如果调用该函数,它应该返回 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 queryif(testG(grid,-1,0) &amp;&amp; testG(grid,0,-1) 的前两部分对于上面的二维数组不会返回 true,因为数字 4 的西部和北部超出了界限。 如何优化我的代码,以便如果索引的一部分超出范围但如果其他查询正确则应返回 false?

提前致谢。

【问题讨论】:

标签: c++ arrays


【解决方案1】:

您似乎想判断每个单元格是否是以下之一:

  • 越界
  • 值为0
  • 值为 11

要实现这一点,函数testG 应该返回true 不仅适用于“具有值0”和“具有值11”的情况,还应该返回“越界”的情况。

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

【讨论】:

    【解决方案2】:
    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;
    }
    

    这会尝试将相邻的入界逻辑与测试逻辑分开。

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 1970-01-01
      • 2020-07-30
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多