我想从以下矩阵中打印对角线
XVSOKG
WTPLHD
UQMIEB
RNJFCA
从右下角开始,因此输出应为A,B,C,D等。 我写下了元素和跟随这样的索引 A [3,5],B [2,5],C [3,4],D [1,5],E [2,4],F [3,3]等,但我找不到任何从这个模式。我怎么想这样做?
答案 0 :(得分:1)
事实上,模式非常简单,问题是您需要了解边界。我做了一个能够完成你所寻找的功能(如果我没有误解,你发布的矩阵你想要打印字母表)。 不幸的是,我没有在C#中做任何设置,所以我用Java做了,希望你能简化它并轻松移植它。
我测试了不同大小的矩阵,但是......你知道。如果可以,请进行测试。
使用以下矩阵:
String[][] matrix = new String[][]{
{"X","V","S","O","K","G"},
{"W","T","P","L","H","D"},
{"U","Q","M","I","E","B"},
{"R","N","J","F","C","A"}
};
结果是:
3 - 5 = A
2 - 5 = B
3 - 4 = C
1 - 5 = D
2 - 4 = E
3 - 3 = F
0 - 5 = G
1 - 4 = H
2 - 3 = I
3 - 2 = J
0 - 4 = K
1 - 3 = L
2 - 2 = M
3 - 1 = N
0 - 3 = O
1 - 2 = P
2 - 1 = Q
3 - 0 = R
0 - 2 = S
1 - 1 = T
2 - 0 = U
0 - 1 = V
1 - 0 = W
0 - 0 = X
(这看起来很长,但主要是评论)
/**
* Prints the diagonals of a matrix from bottom right to top left.
*
* @param matrix the matrix to print
*/
public static void printDiagonals(String[][] matrix){
// extract the width and the height of the matrix
int width = matrix[0].length;
int height = matrix.length;
/**
* these are the pointers that go through the matrix, we inicialize it
* in the bottom right corner
*/
int xIndex = width - 1;
int yIndex = height - 1;
/**
* these are auxiliar pointers to let me trace in what diagonal is the
* next, they are optional but help making the code more clear; I
* initialize it with the position above the bottom right corner
*/
int startingX = xIndex;
int startingY = yIndex - 1;
//while we have not reach the top left corner
while (xIndex >= 0 && yIndex >= 0){
// print the current index and the value, here change it with watever you need
System.out.println(yIndex + " - " + xIndex + " = " + matrix[yIndex][xIndex]);
/**
* as we are moving diagonally to the bottom left we achieve this by
* decreasing the x index and increasing the Y index
*/
xIndex--;
yIndex++;
//if we hit one of the borders
if (yIndex == height || xIndex < 0){
//move the indices to the next diagonal
yIndex = startingY;
xIndex = startingX;
//then we adjust the next diagonal
if (startingY > 0){
startingY--;
} else {
startingX--;
}
}
}
}