这应该是一个相当简单的问题,但我似乎无法弄清楚如何获取非方矩阵的所有对角线。
我已经有了我认为的反对角线(示例位于: https://stackoverflow.com/a/33769730 ),但我也需要相反的对角线。
数组示例:
1 2 3 4
5 6 7 8
9 10 11 12
当前输出:
[1], [2,5], [3,6,9], [4,7,10], [8,11], [12]
预期的额外输出:
[4], [3,8], [2,7,12], [1,6,11], [5,10], [9]
我正在寻找更多伪代码,以便我可以更好地理解这一点。
编辑:我必须获得反对角线的代码(因为似乎没有人想要点击链接)
int ndiags = width + height - 1;
System.out.println("---");
for (int diag = 0; diag < ndiags; diag++) {
int row_stop = Math.max(0, diag - width + 1);
int row_start = Math.min(diag, height - 1);
for (int row = row_start; row >= row_stop; row--) {
// on a given diagonal row + col = constant "diag"
// diag labels the diagonal number
int col = diag - row;
System.out.println(col + "," + row);
relax(col, row);
}
System.out.println("---");
}
我尝试了以下方法,但仍然只是得到反对角线:
int ndiags = width + height - 1;
System.out.println("---");
for (int diag = 0; diag < ndiags; diag++) {
int row_stop = Math.max(0, diag - height + 1);
int row_start = Math.min(diag, width - 1);
for (int row = row_start; row >= row_stop; row--) {
// on a given diagonal row + col = constant "diag"
// diag labels the diagonal number
int col = diag - row;
System.out.println(col + "," + row);
relax(col, row);
}
System.out.println("---");
}
最佳答案
您可以将此代码推广到任何矩阵...现在它会打印上述指定矩阵的正确输出
输出:[4][3 8][2 7 12][5 10][9]
class Diagonal
{
public static void main(String[] args)
{
int r=3,c=4;
int Mat[][]={{1,2,3,4},{5, 6 ,7 ,8},{9,10,11,12}};
int x,y;
for(int i=c-1;i>0;i--)
{
y=i;x=0;
System.out.print("[");
while(y<c)
{
System.out.print(Mat[x][y]+" ");
x++;y++;
}
System.out.print("] ");
}
for(int i=1;i<r;i++)
{
x=i;y=0;
System.out.print("[");
while(x<r)
{
System.out.print(Mat[x][y]+" ");
x++;y++;
}
System.out.print("] ");
}
}
}
对于反对角线:
输出:[1][2 5][3 6 9][4 7 10][8 11][12]
class Diagonal
{
public static void main(String[] args)
{
int r=3,c=4;
int Mat[][]={{1,2,3,4},{5, 6 ,7 ,8},{9,10,11,12}};
int x,y;
for(int i=0;i<c;i++)
{
y=i;x=0;
System.out.print("[");
while(y>=0 && x<r)
{
System.out.print(Mat[x][y]+" ");
x++;y--;
}
System.out.print("] ");
}
for(int i=1;i<r;i++)
{
x=i;y=c-1;
System.out.print("[");
while(x<r)
{
System.out.print(Mat[x][y]+" ");
x++;y--;
}
System.out.print("] ");
}
}
}
关于java - 非方阵中的对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36037764/