对角线读取矩阵的算法(所有对角线)



我需要一个可以对角线读取矩阵(所有对角线(的算法。

输入和输出示例:

输入:

matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
]

输出必须如下所示:

["a", "eb", "ifc", "mjgd", "nkh", "ol","p"]

谢谢你的帮助。

考虑这个问题的最佳方法是单个对角线上的每个单元格必须满足x+y=d其中 d 是对角线的索引(从 0 到 n+m-2(包括 0 到 n+m-2(。

你可以循环 d 和每个 d 循环 x 使用上面的等式我们得到:y=d-x.我建议你拿起纸和笔,自己推导出x的约束。

无论如何,这是工作代码:

matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
]
n = len(matrix)
m = len(matrix[0])

res = []
for d in range(n+m-1):
cur = ""
for x in range(max(0, d-m+1),min(n, d+1)):
print(x, d-x)
cur = matrix[x][d-x] + cur
print('---')
res.append(cur)
print(res)

n行数(或列数(, 那么对角线的数量是2*n-1

对于每个字符串的第一个字符,我们沿着第一列向下, 到达左下角后,我们开始穿过底行

在向字符串添加字符时,对于我们所在的每个[row][column],我们需要转到的下一个[row-1][column+1]

这里有一个示例 java 代码,它将对角线作为字符串添加到数组中,然后将数组打印到 stdout

public static void main(String[] args){
int n = 4;  // number of rows
String array[] = new String[2*n-1];  // array to hold the diagonals
int arrayIndex = 0; 
for (int i = 0; i < 2*n-1; i++) {
if (i < n) {  // until we reach the bottom left corner
int row = i;  // for each row
int column = 0;  // start from the left side
String tmp = "";
while (row >= 0)
tmp += m[row--][column++];
array[arrayIndex++] = tmp;
}
else {  // after we've reached the bottom left corner
int row = n-1;  // start from the bottom row
int column = i-n+1;  // for each column
String tmp = "";
while (column < n)
tmp += m[row--][column++];
array[arrayIndex++] = tmp;
}
}
// prints out the array
for (String s : array)
System.out.print(s + " ");
System.out.print("n");
}
static String m[][] = {
{"a", "b", "c", "d"},
{"e", "f", "g", "h"},
{"i", "j", "k", "l"},
{"m", "n", "o", "p"}
};

这是标准输出的样子

a eb ifc mjgd nkh ol p  

希望这对:)有所帮助

最新更新