繁体   English   中英

从二维数组的给定索引中找到对角线元素的总和

[英]find sum of diagonal elements from given index in 2d array

我必须构造一个包含N,M行和列(N&M <= 5)的2d数组,然后用户输入某个索引(位置),例如2,3(matrix [2] [3]),假设两个数字在矩阵的范围内。 从那时起,我必须找到经过该数字的左右对角线的总和,但是该数字不包括在总和中。

例如,二维数组是myArray [3] [3]

*1* 15 *2*
2 *71* 8
*5* 22 *5*

因此,用户输入1,1,即myArray [1] [1],在这种情况下为数字71,总和为1 + 5 + 2 + 5 ...而且我的问题是我如何才能找到没有这些对角线越界。

For the left top i would go:
row--
column--
while(row >= 0|| column >= 0)

For left bottom:
row++
colum++
while(row < N || column < M)

for right top:
row--
column++
while(row >= 0 || column < M)

for right bottom:
row++
column--
while(row < N || column >=0)

(这是错误的书面伪代码,对不起)

当我输入不在顶行或底行中的数字时,它会很好地工作,但是如果它们位于该行中,则程序会停止。

您拥有的基本上是好的伪代码。 我首先想到的是,在确定位置是否超出范围时,应使用&&而不是||。

您还需要采取某种方式尽早离开,以防其位置不正确。 下面是我迅速写出的一些代码,看起来似乎一目了然-我遍历了所有可能的起始位置,包括超出范围的位置。

#include <iostream>

const int N = 3;
const int M = 4;
int matrix[N][M] = {
        { 0, 1, 2, 3 },
        { 4, 5, 6, 7 },
        { 8, 9, 10, 11 }
};

int directional_sum(int row, int column, int row_inc, int column_inc)
{
    int sum = 0;

    if (row < 0 || column < 0 || row >= N || column >= M)
        return sum;

    int temp_row = row + row_inc;
    int temp_column = column + column_inc;
    while (temp_row >= 0 && temp_column >= 0 && temp_row < N && temp_column < M)
    {
        sum += matrix[temp_row][temp_column];

        temp_row += row_inc;
        temp_column += column_inc;
    }

    return sum;
}

int diagonal_sum(int row, int column)
{
    int sum = 0;
    sum += directional_sum(row, column,  1,  1);
    sum += directional_sum(row, column,  1, -1);
    sum += directional_sum(row, column, -1,  1);
    sum += directional_sum(row, column, -1, -1);

    return sum;
}

int main()
{
    for (int i = -1; i <= N; i++)
    {
        for (int j = -1; j <= M; j++)
        {
            std::cout << "Sum for [" << i << ", " << j << "]: " << diagonal_sum(i, j) << std::endl;
        }
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM