处理矩阵的边界单元格 [英] Process border cells of matrix

查看:29
本文介绍了处理矩阵的边界单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理 nxn 矩阵的每个边界单元格.例如,对于 int array[5][5]; 算法应该处理每个 x 元素,所以它具有形式

I would like to process every border cell of a nxn matrix. For example, for int array[5][5]; algorithm should process every x element, so it has the form

   x x x x x 
   x - - - x
   x - - - x
   x - - - x
   x x x x x

处理这些细胞的最佳方法是什么?如果它是一个 3 维数组呢?提前致谢,对矩阵表示表示抱歉.

What's the best way to process this cells? What about if it is a 3-dimensional array? Thanks in advance, and sorry for the matrix representation.

编辑我我只想使用一个循环以避免嵌套循环或递归.

Edit I I would like to use only one loop in order to avoid nesting loops or recursion.

推荐答案

想象一下触摸每个元素都有其成本,而您只想触摸边框元素.

Imagine touching each element has its cost and you want only touch border elements.

显然,这不是一般优化.但是我在图像处理方面有很好的表现.我的意思是,视情况而定,在您的情况下进行测试并做出决定.

Obviously, it's not a general optimization. But I had a good performance with this, in an image processing. I mean, it depends, test it in your case and decide.

在二维数组中,您可以使 ptr 指向矩阵并逐步进行.

In 2D arrays you can make a ptr points to the matrix and incrementally progresses.

void process(char i)
{
    cout << i;
}

int main()
{
    const int N = 5;
    char mat[N][N] = {
        {'a', 'b', 'c', 'd', 'e'},
        {'f', '-', '-', '-', 'g'},
        {'h', '-', '-', '-', 'i'},
        {'j', '-', '-', '-', 'k'},
        {'l', 'm', 'n', 'o', 'p'}
    };

    char *ptr = (char*) mat;

    for (int i = 0; i < N - 1; ++i) // Process first row
        process(*ptr++);

    for (int i = 0; i < N - 2; ++i) // Process column borders
    {
        process(*ptr);
        process(*(ptr + 1));
        ptr += N;
    }

    for (int i = 0; i <= N; ++i)    // Process last row
        process(*ptr++);

    cout << endl;
}

输出:

abcdefghijklmnop

abcdefghijklmnop

这篇关于处理矩阵的边界单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆