我必须找到数组中元素的数量严格大于与其直接相邻的所有元素。
在数据中:
4
1 5 1 1
2 1 2 3
1 3 4 2
2 1 2 1
输出数据:5
The elements in the matrix that comply with the rule are: 5 2 3 4 2
我的代码:int main()
{
unsigned int n = 0, t[20][20] = { 0 };
std::cin >> n;
for (unsigned int i = 0; i < n; i++)
{
for (unsigned int j = 0; j < n; j++)
{
std::cin >> t[i][j];
}
}
/*
* 00 01 02
* 10 11 12
* 20 21 22
*/
unsigned int c = 0;
for (unsigned int i = 0; i < n; i++)
{
for (unsigned int j = 0; j < n; j++)
{
if (t[i][j] > t[i][j - 1] && t[i][j] > t[i][j + 1] && t[i][j] > t[i - 1][j] && t[i][j] > t[i + 1][j])
{
++c;
}
}
}
std::cout << c;
}
我不知道哪里错了。
最佳答案
您不会处理极端情况,例如当您处于网格边界时。您正在尝试访问行/列中具有负索引的单元格。当if else
或i
= 0且j
或i
= n-1时,您可以使用一些j
在代码中进行处理。
或者,您也可以通过使用1行和1列作为缓冲空间来接受输入。
这是您代码的简短工作版本
#include<bits/stdc++.h>
using namespace std;
int main()
{
unsigned int n = 0, t[20][20] = { 0 };
cin >> n;
for (unsigned int i = 1; i <= n; i++)
{
for (unsigned int j = 1; j <= n; j++)
{
cin >> t[i][j];
}
}
unsigned int c = 0;
for (unsigned int i = 1; i <= n; i++)
{
for (unsigned int j = 1; j <= n; j++)
{
unsigned int mx = max({t[i][j-1],t[i][j+1],t[i-1][j],t[i+1][j]});
if (t[i][j] > mx)
{
++c;
}
}
}
cout << c;
}
关于c++ - 在2d数组中找到严格大于与其直接相邻的所有元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64314269/