c++ - 在2d数组中找到严格大于与其直接相邻的所有元素的数量

标签 c++ algorithm

我必须找到数组中元素的数量严格大于与其直接相邻的所有元素。
在数据中:

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 elsei = 0且ji = 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/

相关文章:

algorithm - 使用搜索算法解决难题

algorithm - 一些程序如何画出流畅的线条?

algorithm - 快速排序相同数字的数组

c++ - 从位图中提取像素数据时出现问题

c++ - 如何将 nullptr 作为参数传递?

c++ - 为什么有不同类型的指针?

c++ - mem_fn 到 member 的 mem_fn

c++ - 是否需要在noexcept运算符中进行std::decay?

python - 实现 Erastosthenes 筛的算法

c# - 为什么 LINQ 操作可以比普通循环更快?