矩阵的固定元素

Stationary element of matrix

我正在尝试编写一个函数来检查矩阵是否具有(至少一个)固定元素。如果矩阵的元素的值等于位于它的左侧、右侧、上方和下方的元素的值,则该元素是固定的。

#include <iostream>
#include <vector>
bool Stationary(std::vector < std::vector < int >> a) {
  int total_elements = 0, rows = a.size();
  int up, down, left, right;
  for (auto i: a)
    for (auto j: i)
      total_elements++;
  if (total_elements % rows)
    throw std::range_error("Ragged matrix");
  int columns = total_elements / rows;
  int count = 0;
  for (int i = 0; i < rows; i++)
    for (int j = 0; j < columns; j++) {
      up = a[i][j + 1];
      down = a[i][j - 1];
      right = a[i + 1][j];
      left = a[i - 1][j];
      std::cout << up << " " << down << " " << right << " " << left << " " << a[i][j] << "\n";
      if (up == down == right == left == a[i][j]) return true;
    }
  return false;
}
int main() {
   std::vector<std::vector<int>>a{
      {2,1,3},
      {1,1,1},
      {4,1,5}};
  try {
    if (Stationary(a))
      std::cout << "Yes";
    else std::cout << "No";
  } catch (std::range_error e) {
    std::cout << e.what();
  }
  return 0;
}

我的代码的问题是访问不是矩阵不可分割部分的随机元素,因为使用命令 i+1 或 j+1 我超出了矩阵的框架。能不能不离开矩阵框,帮我修改一下?

问题是您检查了矩阵的边缘,并且在检查 a[-1][0]a[0][-1] 时,在像 a[0][0] 这样的位置,您越界了。而是从 1 开始你的循环并在 size() - 2(含)结束。

另一个建议是不要采用复制整个矩阵的矩阵by-value。取而代之的是const&

示例:

#include <iostream>
#include <stdexcept>
#include <vector>

bool Stationary(const std::vector<std::vector<int>>& a) {
    // with less than 3 rows, it can't have 4 neighbours (left, right, above, below):
    if (a.size() < 3) return false; 

    size_t cols = a[0].size();
    
    for (size_t i = 1; i < a.size(); ++i)
        if (a[i].size() != cols) throw std::range_error("Ragged matrix");

    // start at 1 and end at size() - 2:
    for (size_t y = 1; y < a.size() - 1; ++y) {
        for (size_t x = 1; x < cols - 1; ++x) {

            int value = a[y][x];

            if (value == a[y - 1][x] &&
                value == a[y + 1][x] &&
                value == a[y][x - 1] &&
                value == a[y][x + 1]) return true;
        }
    }
    return false;
}

int main() {
    std::vector<std::vector<int>> a{{2, 1, 3},
                                    {1, 1, 1},
                                    {4, 1, 5}};
                                    
    std::cout << Stationary(a) << '\n';
}