3

我试图从矩阵中提取某个方向上的所有对角线,例如右下角。

对于以下矩阵:

A   B   C   D
E   F   G   H
I   L   M   N

预期的结果应该是

[ [A F M], [B G N], [C H], [D], [E L], [I] ]

欢迎使用通用方法。

我使用的语言是Java。

谢谢!

编辑

String[] grid = {"SUGAR", 
                 "GLASS", 
                 "MOUSE"};

for( int k = 0; k < grid.length; k++ )
{   
    StringBuffer buffer = new StringBuffer( );

    for( int i = 0; i < grid.length
                && i+k < grid[0].length( ); i++ )
    {
        buffer.append( grid[i].charAt(i+k) );
    }

    trie.addWord( buffer.toString() );
}

添加到特里的输出词是

[ "SLU" "UAS" "GSE" ]

存储在 trie 中的预期字符串(顺序无关紧要)

[ "SLU" "UAS" "GSE" "GO" "M" "AS" "R"]
4

4 回答 4

2

如果您的数据是表格形式,您可以将矩阵向上扫描第一列,然后在第一行左侧。

final String[M][N] mtx = { ... };

public List<List<String>> diagonalize() {
    final List<List<String>> diags = new ArrayList<>();
    for (int row = M - 1; row > 1; --row) {
        diags.add(getDiagonal(row, 0));
    }
    for (int col = 0; col < N; ++col) {
        diags.add(getDiagonal(0, col));
    }
    return diags;
}

private List<String> getDiagonal(int x, int y) {
    final List<String> diag = new ArrayList<>();
    while (x < M && y < N) {
        diag.add(mtx[x++][y++]);
    }
    return diag;
}
于 2013-06-11T14:14:18.643 回答
2

这是一个有趣的问题。

很容易陷入嵌套循环。

我注意到如果我把这些词放在一个字符串中,就会出现一种模式。

以 OP 为例,“SUGAR”、“GLASS”、“MOUSE”这三个词连接在一起形成 SUGARGLASSMOUSE。

这是我需要从连接字符串中获取的字符的从零开始的字符位置。我已经把它们排成一行,这样你就可以更容易地看到图案。

          10     M
     5    11     GO
0    6    12     SLU
1    7    13     UAS
2    8    14     GSE
3    9           AS
4                R

看到图案了吗?我有 3 个索引,由 5 次迭代组成。我有 3 个单词,由 5 个字母组成。

对角词的数量是letters + words - 1。我们减去 1,因为字符位置 0 的第一个字母只使用一次。

这是我运行的测试的结果。

[ "SUGAR" "GLASS" "MOUSE" "STATE" "PUPIL" "TESTS" ]
[ "T" "PE" "SUS" "MTPT" "GOAIS" "SLUTL" "UASE" "GSE" "AS" "R" ]

[ "SUGAR" "GLASS" "MOUSE" ]
[ "M" "GO" "SLU" "UAS" "GSE" "AS" "R" ]

这是代码:

import java.util.ArrayList;
import java.util.List;

public class Matrix {

    public static final int DOWN_RIGHT = 1;
    public static final int DOWN_LEFT = 2;
    public static final int UP_RIGHT = 4;
    public static final int UP_LEFT = 8;

    public String[] getMatrixDiagonal(String[] grid, int direction) {
        StringBuilder builder = new StringBuilder();
        for (String s : grid) {
            builder.append(s);
        }
        String matrixString = builder.toString();

        int wordLength = grid[0].length();
        int numberOfWords = grid.length;
        List<String> list = new ArrayList<String>();


        if (wordLength > 0) {
            int[] indexes = new int[numberOfWords];

            if (direction == DOWN_RIGHT) {
                indexes[0] = matrixString.length() - wordLength;
                for (int i = 1; i < numberOfWords; i++) {
                    indexes[i] = indexes[i - 1] - wordLength;
                }

                int wordCount = numberOfWords + wordLength - 1;

                for (int i = 0; i < wordCount; i++) {
                    builder.delete(0, builder.length());
                    for (int j = 0; (j <= i) && (j < numberOfWords); j++) {
                        if (indexes[j] < wordLength * (wordCount - i)) {
                            char c = matrixString.charAt(indexes[j]);
                            builder.append(c);
                            indexes[j]++;
                        }
                    }
                    String s = builder.reverse().toString();
                    list.add(s);
                }
            }

            if (direction == DOWN_LEFT) {
                // Exercise for original poster
            }

            if (direction == UP_RIGHT) {
                // Exercise for original poster
            }

            if (direction == UP_LEFT) {
                // Exercise for original poster
                // Same as DOWN_RIGHT with the reverse() removed
            }
        }

        return list.toArray(new String[list.size()]);
    }

    public static void main(String[] args) {
        String[] grid1 = { "SUGAR", "GLASS", "MOUSE", "STATE", "PUPIL", "TESTS" };
        String[] grid2 = { "SUGAR", "GLASS", "MOUSE" };

        Matrix matrix = new Matrix();
        String[] output = matrix.getMatrixDiagonal(grid1, DOWN_RIGHT);
        System.out.println(createStringLine(grid1));
        System.out.println(createStringLine(output));

        output = matrix.getMatrixDiagonal(grid2, DOWN_RIGHT);
        System.out.println(createStringLine(grid2));
        System.out.println(createStringLine(output));
    }

    private static String createStringLine(String[] values) {
        StringBuilder builder = new StringBuilder();
        builder.append("[ ");

        for (String s : values) {
            builder.append("\"");
            builder.append(s);
            builder.append("\" ");
        }

        builder.append("]");

        return builder.toString();
    }

}
于 2013-06-11T15:45:36.763 回答
2
    String[] grid = {"SUGAR", 
             "GLASS", 
             "MOUSE"};
    System.out.println("Result: " + Arrays.toString(diagonals(grid)));

public static String[] diagonals(String[] grid) {
    int nrows = grid.length;
    int ncols = grid[0].length();
    int nwords = ncols + nrows - 1;
    String[] words = new String[nwords];
    int iword = 0;
    for (int col = 0; col < ncols; ++col) {
        int n = Math.min(nrows, ncols - col);
        char[] word = new char[n];
        for (int i = 0; i < n; ++i) {
            word[i] = grid[i].charAt(col + i);
        }
        words[iword] = new String(word);
        ++iword;
    }
    for (int row = 1; row < nrows; ++row) {
        int n = Math.min(ncols, nrows - row);
        char[] word = new char[n];
        for (int i = 0; i < n; ++i) {
            word[i] = grid[row + i].charAt(i);
        }
        words[iword] = new String(word);
        ++iword;
    }
    assert iword == nwords;
    return words;
}

Result: [SLU, UAS, GSE, AS, R, GO, M]

首先是列上第一个元素的循环。然后在行上循环,跳过第 0 行。两个循环中的代码非常对称。没什么太难的。假设所有字符串都具有相同的长度。

作为一个循环:

public static String[] diagonals(String[] grid) {
    int nrows = grid.length;
    int ncols = grid[0].length();
    int nwords = ncols + nrows - 1;
    String[] words = new String[nwords];

    // Position of first letter in word:
    int row = 0;
    int col = ncols - 1;

    for (int iword = 0; iword < nwords; ++iword) {
        int n = Math.min(nrows - row, ncols - col);
        char[] word = new char[n];
        for (int i = 0; i < n; ++i) {
            word[i] = grid[row + i].charAt(col + i);
        }
        words[iword] = new String(word);

        if (col > 0) {
            --col;
        } else {
            ++row;
        }
    }
    return words;
}

的声明word可以被带到循环之外。只需使用 (row, col) 左侧和顶部边缘即可。

于 2013-06-11T16:09:16.197 回答
0

您可以使用二维数组表示您的矩阵,

char[][] 矩阵 = char[][]

然后你可以使用 for 循环来遍历它并提取你想要的输出,你的算法的输入将是你想要的对角线方向。

对于前; 一种可能的输入是正确的

根据可能的输入,您必须决定如何遍历循环初始条件和终止条件。

从最后一列第一行字符开始

r = 0,c = 库仑计数 -1;

终止条件将是 first_column 最后一行索引处的字符。

r = row_count -1,c = 0;

在最后一行或最后一列读取字符时的每次迭代都是子循环的终止

于 2012-05-23T04:55:28.043 回答