【发布时间】:2016-07-06 21:12:30
【问题描述】:
可以按照下图打印矩阵值
【问题讨论】:
-
是的,有可能。试一试,然后用你的努力回来:-)
-
如果您尝试过但不起作用,请分享您的代码。
-
我没有任何代码,正在处理它。
可以按照下图打印矩阵值
【问题讨论】:
据我了解,可以使用以下帮助函数解决该问题,该函数计算下一个条目的索引。语法是 C#,但在 Java 中应该类似,m 和 n 应该是各自的矩阵维度。这个想法是检查所需的主要方向是左下还是右上;如果到达矩阵的边缘(必须事先检查),则分别将其修改为右和下。该实现假定行和列的索引从零开始。
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;
}
【讨论】:
就个人而言,我更喜欢@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;
}
【讨论】: