矩阵的固定元素
我正在尝试编写一个功能,该功能将检查矩阵是否具有(至少一个)固定元素。如果矩阵的元素值等于位于左侧,右,上方和下方的元素的值的值,则是静止的。
#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,我会超越矩阵的框架。您能帮我修改它而不离开矩阵框架吗?
I'm trying to write a function which will check if matrix has (at least one) stationary elements. An element of a matrix is stationary if its value is equal to the value of the elements located to the left, right, above and below it.
#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;
}
Problem with my code is access to random elements that are not integral parts of the matrix, because with the command i+1 or j+1 I go beyond the frame of the matrix. Could you help me to modify this without leaving the matrix frame?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您检查矩阵的边缘,并在
a [0] [0]
之类的位置中检查a [-1] [0] 和
a [0] [ - 1]
。而是从1
开始循环,然后以size()-2
(包含)结束。另一个建议是不使用复制整个矩阵的矩阵 by-by-by-by-value 。用
const&amp;/code>取而代之的是。
例子:
The problem is that you check the edges of the matrix and in a position like
a[0][0]
you step out of bounds when checkinga[-1][0]
anda[0][-1]
. Instead start your loops at1
and end atsize() - 2
(inclusive).Another suggestion is to not take the matrix by-value which copies the whole matrix. Take it by
const&
instead.Example: