矩阵:从给定矩阵中获取值

时间:2016-07-06 21:12:31

标签: java c++ c arrays

可以按照下面的图像打印矩阵值

The Matrix

2 个答案:

答案 0 :(得分:1)

根据我的理解,可以使用以下辅助函数来解决问题,该辅助函数计算下一个条目的索引。语法是C#,但在Java中应该类似,其中mn应该是相应的矩阵维度。我们的想法是检查所需的主方向是左下还是右上;如果到达矩阵的边缘(必须事先检查),则分别将其修改为向右和向下。该实现假定行和列的从零开始索引。

public struct Cell
{
    public int Row;
    public int Col;
}

public static Cell GetNext(Cell iCell)
{
    Cell Result;
    if (( iCell.Row + iCell.Col ) % 2 == 0)
    {
        if (iCell.Col == n - 1)
            Result = new Cell { Row = iCell.Row + 1, Col = n - 1 };
        else if (iCell.Row == 0)                    
            Result = new Cell { Row = 0, Col = iCell.Col + 1 };
        else
            Result = new Cell { Row = iCell.Row - 1, Col = iCell.Col + 1 };
    }
    else
    {
        if (iCell.Row == m - 1)
            Result = new Cell { Row = m - 1, Col = iCell.Col + 1 };
        else if (iCell.Col == 0)
            Result = new Cell { Row = iCell.Row + 1, Col = 0 };
        else
            Result = new Cell { Row = iCell.Row + 1, Col = iCell.Col - 1 };
    }
    return Result;
}

答案 1 :(得分:0)

就个人而言,我更喜欢@Codor的方法。我以为我也会把这个Java函数放在混合中。

[注意:我没有编译或运行它。但是,我认为它应该起作用(主要是)。让我知道。 :)]

public static int[] getTraversedArray(int[][] arr) {
     if (arr == null || arr.length == 0) 
        return null;

    # matrix need not be `nxn`
    int l = arr.length - 1, w = arr[0].length - 1;

    # all indices need to be visited
    int[] out = new int[(l + 1) * (w + 1)];

    int indx = 0;
    for (int i = 0; i <= l + w; i++) {
        # "even" index
        if (i % 2 == 0) {
            for (int x = i; x >= 0; x--) {
                # if it is a "valid index", set the value
                # in the output array
                if ((x <= l) && (i - x <= w)) {
                    out[indx] = arr[x][i - x];
                    indx++;
                }
            }
        } 
        # "odd" index
        else {
            for (int x = 0; x <= i; x++) {
                # if it is a "valid index", set the value
                # in the output array
                if ((x <= l) && (i - x <= w)) {
                    out[indx] = arr[x][i - x];
                    indx++;
                }
            }
        }
    }
    return out;
}