如何以不同的方式在Java中读取矩阵数组?

huangapple go评论128阅读模式
英文:

How can I read matrix array different way in Java?

问题

我有一个8x8的矩阵数组。我想按照图片中所示读取矩阵的值(元素)。\n我该怎么做?\n\n我已经像这样定义了数组。\n\njava\npublic static void main(String args[]) {\n int[][] myArray = new int[8][8];\n\n int start = 0;\n\n for (int i = 0; i<8; i++){\n for (int j = 0; j<8; j++) {\n myArray[i][j] = start;\n start++;\n }\n }\n}\n\n\n如何以不同的方式在Java中读取矩阵数组?

英文:

I have a 8x8 matrix array. I want to read matrix values (elements) as shown in the picture.
Ho can I do it?

I've defined array like this.

public static void main(String args[]) {
    int[][] myArray = new int[8][8];

    int start = 0;

    for (int i = 0; i&lt;8; i++){
        for (int j = 0; j&lt;8; j++) {
            myArray[i][j] = start;
            start++;
        }
    }
}

如何以不同的方式在Java中读取矩阵数组?

答案1

得分: 1

public static List<Integer> readMatrix(int[][] matrix) {
    int totalRows = matrix.length;
    int totalCols = matrix[0].length;

    List<Integer> res = new ArrayList<>(totalRows * totalCols);
    List<Integer> diagonal = new ArrayList<>(Math.max(totalRows, totalCols));

    boolean reverseOrder = true;

    for (int col = totalCols - 1; col >= 0; col--) {
        for (int row = 0; row < totalRows && col + row < totalCols; row++)
            diagonal.add(matrix[row][col + row]);

        if (reverseOrder)
            Collections.reverse(diagonal);

        res.addAll(diagonal);
        reverseOrder = !reverseOrder;
        diagonal.clear();
    }

    for (int row = 1; row < totalRows; row++) {
        for (int col = 0; col < totalCols && col + row < totalRows; col++)
            diagonal.add(matrix[col + row][col]);

        if (reverseOrder)
            Collections.reverse(diagonal);

        res.addAll(diagonal);
        reverseOrder = !reverseOrder;
        diagonal.clear();
    }

    return res;
}
英文:
public static List&lt;Integer&gt; readMatrix(int[][] matrix) {
    int totalRows = matrix.length;
    int totalCols = matrix[0].length;

    List&lt;Integer&gt; res = new ArrayList&lt;&gt;(totalRows * totalCols);
    List&lt;Integer&gt; diagonal = new ArrayList&lt;&gt;(Math.max(totalRows, totalCols));

    boolean reverseOrder = true;

    for (int col = totalCols - 1; col &gt;= 0; col--) {
        for (int row = 0; row &lt; totalRows &amp;&amp; col + row &lt; totalCols; row++)
            diagonal.add(matrix[row][col + row]);

        if (reverseOrder)
            Collections.reverse(diagonal);

        res.addAll(diagonal);
        reverseOrder = !reverseOrder;
        diagonal.clear();
    }

    for (int row = 1; row &lt; totalRows; row++) {
        for (int col = 0; col &lt; totalCols &amp;&amp; col + row &lt; totalRows; col++)
            diagonal.add(matrix[col + row][col]);

        if (reverseOrder)
            Collections.reverse(diagonal);

        res.addAll(diagonal);
        reverseOrder = !reverseOrder;
        diagonal.clear();
    }

    return res;
}

答案2

得分: 1

以下是您提供的代码的翻译部分:

public class MatrixTraversal {
    private static int[][] matrix;

    private static void displayElement(int row, int col, int length, int count) {
        System.out.printf("%" + length + "d. 下一个元素 [%" + length + "d][%" + length + "d] = %" + length + "d%n",
                          (count + 1),
                          row,
                          col,
                          matrix[row][col]);
    }

    private static void displayMatrix() {
        int length = getLength();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (j > 0 && j < matrix[i].length) {
                    System.out.print(" ");
                }
                System.out.printf("%" + length + "d", matrix[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    }

    private static int getLength() {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int number = rows * cols;
        int length = (int) (Math.log10(number) + 1);
        return length;
    }

    private static void initMatrix(int rows, int cols) {
        System.out.printf("行数 = %d ,列数 = %d%n", rows, cols);
        System.out.println();
        if (rows > 0 && cols > 0) {
            matrix = new int[rows][cols];
            for (int row = 0; row < rows; row++) {
                for (int col = 0; col < cols; col++) {
                    matrix[row][col] = (row * cols) + col;
                }
            }
            displayMatrix();
        }
        else {
            throw new IllegalArgumentException("行数和列数必须都是正数");
        }
    }

    // 算法:
    // 1. 从第一行,最后一列开始。
    // 2. 移动到同一行的左边列。
    //    a. 如果无法向左移动,向下一行移动,即同一列,下一行。
    //    b. 如果无法向左或向下移动,进入步骤 3。
    // 3. 沿着右下角对角线移动,直到达到最后一行或最后一列。
    //    a. 如果无法向右下移动,进入步骤 4。
    // 4. 移动到下一行,同一列。
    //    a. 如果无法向下移动,向左移动,即同一行,左边列。
    //    b. 如果无法向下或向左移动,进入步骤 5。
    // 5. 沿着左上角对角线移动,直到达到第一行或第一列。
    //    a. 如果无法向左上移动,进入步骤 6。
    // 6. 返回步骤 2。
    // 7. 结束在最后一行,第一列。
    private static void traverse() {
        int length = getLength();
        int total = matrix.length * matrix[0].length;
        System.out.println("总数 = " + total);
        int row = 0;
        int col = matrix[row].length - 1;
        System.out.println("开始列 = " + col);
        int count = 0;
        System.out.printf("%" + length + "d. 第一个元素 [%" + length + "d][%" + length + "d] = %" + length + "d%n",
                          1,
                          row,
                          col,
                          matrix[row][col]);
        count++;
        while (count < total) {
            if (col - 1 >= 0) {
                col--;
                displayElement(row, col, length, count);
                count++;
            }
            else {
                if (row < matrix.length - 1) {
                    row++;
                    displayElement(row, col, length, count);
                    count++;
                }
            }
            while (row < matrix.length - 1 && col < matrix[row].length - 1) {
                row++;
                col++;
                displayElement(row, col, length, count);
                count++;
            }
            if (row < matrix.length - 1) {
                row++;
                displayElement(row, col, length, count);
                count++;
            }
            else {
                if (col - 1 >= 0) {
                    col--;
                    displayElement(row, col, length, count);
                    count++;
                }
            }
            while (row > 0 && col > 0) {
                row--;
                col--;
                displayElement(row, col, length, count);
                count++;
            }
        }
    }

    /**
     * 需要以下两个 &lt;tt&gt;java&lt;/tt&gt; 命令参数(按顺序列出):
     * &lt;ol&gt;
     * &lt;li&gt;矩阵中的行数&lt;/li&gt;
     * &lt;li&gt;矩阵中的列数&lt;/li&gt;
     * &lt;/ol&gt;
     * 
     * @param args - &lt;tt&gt;java&lt;/tt&gt; 命令参数。
     */
    public static void main(String[] args) {
        if (args.length > 1) {
            int rows = Integer.parseInt(args[0]);
            int cols = Integer.parseInt(args[1]);
            initMatrix(rows, cols);
            traverse();
        }
        else {
            System.out.println("参数: &lt;矩阵中的行数&gt; &lt;矩阵中的列数&gt;");
        }
    }
}

这是您提供的代码的翻译版本。如果您有其他问题或需要进一步的帮助,请随时提问。

英文:

Here's my solution. Code contains comments explaining the traversal algorithm.

public class MatrixTraversal {
    private static int[][]  matrix;

    private static void displayElement(int row, int col, int length, int count) {
        System.out.printf(&quot;%&quot; + length + &quot;d. Next  element [%&quot; + length + &quot;d][%&quot; + length + &quot;d] = %&quot; + length + &quot;d%n&quot;,
                          (count + 1),
                          row,
                          col,
                          matrix[row][col]);
    }

    private static void displayMatrix() {
        int length = getLength();
        for (int i = 0; i &lt; matrix.length; i++) {
            for (int j = 0; j &lt; matrix[i].length; j++) {
                if (j &gt; 0  &amp;&amp;  j &lt; matrix[i].length) {
                    System.out.print(&quot; &quot;);
                }
                System.out.printf(&quot;%&quot; + length + &quot;d&quot;, matrix[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    }

    private static int getLength() {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int number = rows * cols;
        int length = (int) (Math.log10(number) + 1);
        return length;
    }

    private static void initMatrix(int rows, int cols) {
        System.out.printf(&quot;rows = %d , columns = %d%n&quot;, rows, cols);
        System.out.println();
        if (rows &gt; 0  &amp;&amp;  cols &gt; 0) {
            matrix = new int[rows][cols];
            for (int row = 0; row &lt; rows; row++) {
                for (int col = 0; col &lt; cols; col++) {
                    matrix[row][col] = (row * cols) + col;
                }
            }
            displayMatrix();
        }
        else {
            throw new IllegalArgumentException(&quot;rows and columns must both be positive&quot;);
        }
    }

    // Algorithm:
    // 1. Start at first row, last column.
    // 2. Go to same row, column to left.
    //    a. If can&#39;t go left, go down one row, i.e. same column, next row.
    //    b. If can&#39;t go left, go to step 3.
    // 3. Go diagonally down and to the right until reach either last row or last column.
    //    a. If can&#39;t go diagonally down and to the right, go to 4.
    // 4. Go to same column, next row.
    //    a. If can&#39;t go down, go left, i.e. same row, column to left.
    //    b. If can&#39;t go left, go to step 5.
    // 5. Go diagonally up and to the left until reach either first row or first column.
    //    a. If can&#39;t go diagonally up and to the left, go to 6.
    // 6. Go back to step 2.
    // 7. Finish at last row, first column.
    private static void traverse() {
        int length = getLength();
        int total = matrix.length * matrix[0].length;
        System.out.println(&quot;Total = &quot; + total);
        int row = 0;
        int col = matrix[row].length - 1;
        System.out.println(&quot;Start col = &quot; + col);
        int count = 0;
        System.out.printf(&quot;%&quot; + length + &quot;d. First element [%&quot; + length + &quot;d][%&quot; + length + &quot;d] = %&quot; + length + &quot;d%n&quot;,
                          1,
                          row,
                          col,
                          matrix[row][col]);
        count++;
        while (count &lt; total) {
            if (col - 1 &gt;= 0) {
                col--;
                displayElement(row, col, length, count);
                count++;
            }
            else {
                if (row &lt; matrix.length - 1) {
                    row++;
                    displayElement(row, col, length, count);
                    count++;
                }
            }
            while (row &lt; matrix.length - 1  &amp;&amp;  col &lt; matrix[row].length - 1) {
                row++;
                col++;
                displayElement(row, col, length, count);
                count++;
            }
            if (row &lt; matrix.length - 1) {
                row++;
                displayElement(row, col, length, count);
                count++;
            }
            else {
                if (col - 1 &gt;= 0) {
                    col--;
                    displayElement(row, col, length, count);
                    count++;
                }
            }
            while (row &gt; 0  &amp;&amp;  col &gt; 0) {
                row--;
                col--;
                displayElement(row, col, length, count);
                count++;
            }
        }
    }

    /**
     * Requires following two &lt;tt&gt;java&lt;/tt&gt; command arguments (in listed order):
     * &lt;ol&gt;
     * &lt;li&gt;number of rows in matrix&lt;/li&gt;
     * &lt;li&gt;number of columns in matrix&lt;/li&gt;
     * &lt;/ol&gt;
     * 
     * @param args - &lt;tt&gt;java&lt;/tt&gt; command arguments.
     */
    public static void main(String[] args) {
        if (args.length &gt; 1) {
            int rows = Integer.parseInt(args[0]);
            int cols = Integer.parseInt(args[1]);
            initMatrix(rows, cols);
            traverse();
        }
        else {
            System.out.println(&quot;ARGS: &lt;# of rows in matrix&gt; &lt;# of columns in matrix&gt;&quot;);
        }
    }
}

Tested on different dimensions including one row and several columns and one column and several rows. Here is the output for an 8x8 matrix.

rows = 8 , columns = 8
0  1  2  3  4  5  6  7
8  9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
Total = 64
Start col = 7
1. First element [ 0][ 7] =  7
2. Next  element [ 0][ 6] =  6
3. Next  element [ 1][ 7] = 15
4. Next  element [ 2][ 7] = 23
5. Next  element [ 1][ 6] = 14
6. Next  element [ 0][ 5] =  5
7. Next  element [ 0][ 4] =  4
8. Next  element [ 1][ 5] = 13
9. Next  element [ 2][ 6] = 22
10. Next  element [ 3][ 7] = 31
11. Next  element [ 4][ 7] = 39
12. Next  element [ 3][ 6] = 30
13. Next  element [ 2][ 5] = 21
14. Next  element [ 1][ 4] = 12
15. Next  element [ 0][ 3] =  3
16. Next  element [ 0][ 2] =  2
17. Next  element [ 1][ 3] = 11
18. Next  element [ 2][ 4] = 20
19. Next  element [ 3][ 5] = 29
20. Next  element [ 4][ 6] = 38
21. Next  element [ 5][ 7] = 47
22. Next  element [ 6][ 7] = 55
23. Next  element [ 5][ 6] = 46
24. Next  element [ 4][ 5] = 37
25. Next  element [ 3][ 4] = 28
26. Next  element [ 2][ 3] = 19
27. Next  element [ 1][ 2] = 10
28. Next  element [ 0][ 1] =  1
29. Next  element [ 0][ 0] =  0
30. Next  element [ 1][ 1] =  9
31. Next  element [ 2][ 2] = 18
32. Next  element [ 3][ 3] = 27
33. Next  element [ 4][ 4] = 36
34. Next  element [ 5][ 5] = 45
35. Next  element [ 6][ 6] = 54
36. Next  element [ 7][ 7] = 63
37. Next  element [ 7][ 6] = 62
38. Next  element [ 6][ 5] = 53
39. Next  element [ 5][ 4] = 44
40. Next  element [ 4][ 3] = 35
41. Next  element [ 3][ 2] = 26
42. Next  element [ 2][ 1] = 17
43. Next  element [ 1][ 0] =  8
44. Next  element [ 2][ 0] = 16
45. Next  element [ 3][ 1] = 25
46. Next  element [ 4][ 2] = 34
47. Next  element [ 5][ 3] = 43
48. Next  element [ 6][ 4] = 52
49. Next  element [ 7][ 5] = 61
50. Next  element [ 7][ 4] = 60
51. Next  element [ 6][ 3] = 51
52. Next  element [ 5][ 2] = 42
53. Next  element [ 4][ 1] = 33
54. Next  element [ 3][ 0] = 24
55. Next  element [ 4][ 0] = 32
56. Next  element [ 5][ 1] = 41
57. Next  element [ 6][ 2] = 50
58. Next  element [ 7][ 3] = 59
59. Next  element [ 7][ 2] = 58
60. Next  element [ 6][ 1] = 49
61. Next  element [ 5][ 0] = 40
62. Next  element [ 6][ 0] = 48
63. Next  element [ 7][ 1] = 57
64. Next  element [ 7][ 0] = 56

答案3

得分: 0

以下是您提供的内容的翻译:


如何解决任何编程问题?一步一步来。

按照您图片中的路径,让我们列出前几个整数数组下标。

0, 7
0, 6
1, 7
2, 7
1, 6
0, 5
0, 4
1, 5
2, 6
3, 7

您需要列出足够多的下标以看到所形成的模式。

一个可能的解决方案是在不同的数组中编码这些下标。不幸的是,这个解决方案会将您锁定在一个 8 x 8 的矩阵中。

因此,让我们编写一些代码来获取矩阵的前几个值。这些代码可能不够优美。我们仍在试图找出这个模式。

import java.util.Arrays;

public class ArrayWalk {

    public static void main(String args[]) {
        int height = 8;
        int width = 8;

        ArrayWalk aw = new ArrayWalk();
        int[][] myArray = aw.createArray(height, width);
        int[] values = aw.walkArray(myArray);

        System.out.println(Arrays.toString(values));
    }

    private int[][] createArray(int height, int width) {
        int[][] myArray = new int[height][width];

        int start = 0;

        for (int h = 0; h < height; h++) {
            for (int w = 0; w < width; w++) {
                myArray[h][w] = start;
                start++;
            }
        }

        return myArray;
    }

    // walkArray方法的实现在此处省略

}

正如您所见,我们已经确定需要设置矩阵的宽度和高度,并且需要返回一个整数数组来保存矩阵的值。

到目前为止还好。

更重要的是,我们看到了一个正在发展的模式。让我们只看下标部分。

w--
h++
w++   (一次)
h++
h--
w--   (两次)

这个模式重复出现,唯一的例外是双重下标会重复一次、两次、三次,一直到七次(宽度减一)。然后,双重下标会重复六次、五次、四次等。

顶行和底行总是向左移动。第一列和最后一列总是向下移动。

现在,在这一点上,我不确定我刚刚说的对于一个矩形矩阵是否有效。我相当确定它对于一个正方形矩阵有效。

让我们根据我们获得的知识编写一个辅助方法。这个模式是一个工厂模式。

private Dimension[] createIncrements() {
    Dimension[] increments = new Dimension[4];
    increments[0] = new Dimension(-1, 0);
    increments[1] = new Dimension(1, 1);
    increments[2] = new Dimension(0, 1);
    increments[3] = new Dimension(-1, -1);
    return increments;
}

一个 java.awt.Dimension 包含一个宽度和一个高度。所以,我们定义了我们在代码模式中看到的四个增量。然后,我们可以循环遍历这些增量。关键是要跟踪我们需要使用第一个和第三个(从零开始的)增量的次数。我们将不得不从1计数到7,然后再从7倒数回1。

我已经进行了几个小时的实验。这是一个难解的问题。我将在明天继续。

我希望到目前为止我给您的描述是有帮助的。

补充编辑:我不确定我是否会想出其他答案中的算法。我最终只是写了一些代码来测试不同的数组大小。

以下是一个测试的结果。

-------------------
|   0 |   1 |   2 |
-------------------
|   3 |   4 |   5 |
-------------------
|   6 |   7 |   8 |
-------------------
[2, 1, 5, 8, 4, 0, 3, 7, 6]

另一个测试

-------------------------------
|   0 |   1 |   2 |   3 |   4 |
-------------------------------
|   5 |   6 |   7 |   8 |   9 |
-------------------------------
[4, 3, 9, 8, 2, 1, 7, 6, 0, 5]

最后,来自图片的 8 x 8 测试。

-------------------------------------------------
|   0 |   1 |   2 |   3 |   4 |   5 |   6 |   7 |
-------------------------------------------------
|   8 |   9 |  10 |  11 |  12 |  13 |  14 |  15 |
-------------------------------------------------
|  16 |  17 |  18 |  19 |  20 |  21 |  22 |  23 |
-------------------------------------------------
|  24 |  25 |  26 |  27 |  28 |  29 |  30 |  31 |
-------------------------------------------------
|  32 |  33 |  34 |  35 |  36 |  37 |  38 |  39 |
-------------------------------------------------
|  40 |  41 |  42 |  43 |  44 |  45 |  46 |  47 |
-------------------------------------------------
|  48 |  49 |  50 |  51 |  52 |  53 |  54 |  55 |
-------------------------------------------------
|  56 |  57 |  58 |  59 |  60 |  61 |  62 |  63 |
-------------------------------------------------
[7, 6, 15, 23, 14, 5, 4, 13, 22, 31, 39, 30, 21, 12, 3, 2, 11, 20, 29, 38, 
47, 
<details>
<summary>英文:</summary>
How do you solve any coding problem?  One step at a time.
Following the path in your picture, let&#39;s list the first several integer array subscripts.  
0, 7
0, 6
1, 7
2, 7
1, 6
0, 5
0, 4
1, 5
2, 6
3, 7
You need to list enough subscripts to see the pattern that develops.
One possible solution would be to code the subscripts in a different array.  Unfortunately, this solution would lock you into an 8 x 8 matrix.
So, let&#39;s write some code to get the first few values of the matrix.  It&#39;s not going to be pretty code.  We&#39;re still trying to figure out the pattern.
import java.util.Arrays;
public class ArrayWalk {
public static void main(String args[]) {
int height = 8;
int width = 8;
ArrayWalk aw = new ArrayWalk();
int[][] myArray = aw.createArray(height, width);
int[] values = aw.walkArray(myArray);
System.out.println(Arrays.toString(values));
}
private int[][] createArray(int height, int width) {
int[][] myArray = new int[height][width];
int start = 0;
for (int h = 0; h &lt; height; h++) {
for (int w = 0; w &lt; width; w++) {
myArray[h][w] = start;
start++;
}
}
return myArray;
}
private int[] walkArray(int[][] myArray) {
int height = myArray.length;
int width = myArray[0].length;
int length = height * width;
int[] values = new int[length];
int index = 0;
int h = 0;
int w = width - 1;
values[index++] = myArray[h][w];
w--;
values[index++] = myArray[h][w];
h++;
w++;
values[index++] = myArray[h][w];
h++;
values[index++] = myArray[h][w];
h--;
w--;
values[index++] = myArray[h][w];
h--;
w--;
values[index++] = myArray[h][w];
w--;
values[index++] = myArray[h][w];
h++;
w++;
values[index++] = myArray[h][w];
h++;
w++;
values[index++] = myArray[h][w];
h++;
w++;
values[index++] = myArray[h][w];
h++;
values[index++] = myArray[h][w];
h--;
w--;
values[index++] = myArray[h][w];
h--;
w--;
values[index++] = myArray[h][w];
h--;
w--;
values[index++] = myArray[h][w];
h--;
w--;
values[index++] = myArray[h][w];
return values;
}
}
As you can see, we&#39;ve determined that we need to set the width and height of the matrix, and we need to return an integer array to hold the matrix values.
So far, so good.
More importantly, we see a pattern developing.  Let&#39;s just look at the subscripts.
w--
h++
w++   (once)
h++
h--
w--   (twice)
This pattern repeats, with the exception that the double subscript repeats once, twice, three times, up to seven times (the width - one).  Then the double subscript repeats six, five, four, etc. times.
The top row and bottom row always shift to the left.  The first column and last column always shift down.
Now, at this point, I&#39;m not sure if what I just said works for a rectangular matrix.  I&#39;m pretty sure that it works for a square matrix.
Let&#39;s code a helper method with the knowledge we&#39;ve gained.  This pattern is a factory pattern.
private Dimension[] createIncrements() {
Dimension[] increments = new Dimension[4];
increments[0] = new Dimension(-1, 0);
increments[1] = new Dimension(1, 1);
increments[2] = new Dimension(0, 1);
increments[3] = new Dimension(-1, -1);
return increments;
}
A java.awt.Dimension holds a width and a height.  So, we define the four increments that we saw in the code pattern.  We can then cycle through these increments.  The trick will be keeping track of how many times we need to increment using the first and third (zero-based) increment.  We&#39;ll have to count up from 1 to 7 and back down to 1.
I&#39;ve been experimenting for several hours now.  This is a hard problem to solve.  I&#39;ll pick up where I left off tomorrow.
I hope the description that I&#39;ve given you so far is helpful.
Edited to add: I&#39;m not sure I&#39;d have come up with the algorithm in the other answers.  All I did ultimately was to write some code to test different array sizes.
Here are the results of one test.
-------------------
|   0 |   1 |   2 |
-------------------
|   3 |   4 |   5 |
-------------------
|   6 |   7 |   8 |
-------------------
[2, 1, 5, 8, 4, 0, 3, 7, 6]
Another test
-------------------------------
|   0 |   1 |   2 |   3 |   4 |
-------------------------------
|   5 |   6 |   7 |   8 |   9 |
-------------------------------
[4, 3, 9, 8, 2, 1, 7, 6, 0, 5]
Finally, the 8 x 8 test from the image.
-------------------------------------------------
|   0 |   1 |   2 |   3 |   4 |   5 |   6 |   7 |
-------------------------------------------------
|   8 |   9 |  10 |  11 |  12 |  13 |  14 |  15 |
-------------------------------------------------
|  16 |  17 |  18 |  19 |  20 |  21 |  22 |  23 |
-------------------------------------------------
|  24 |  25 |  26 |  27 |  28 |  29 |  30 |  31 |
-------------------------------------------------
|  32 |  33 |  34 |  35 |  36 |  37 |  38 |  39 |
-------------------------------------------------
|  40 |  41 |  42 |  43 |  44 |  45 |  46 |  47 |
-------------------------------------------------
|  48 |  49 |  50 |  51 |  52 |  53 |  54 |  55 |
-------------------------------------------------
|  56 |  57 |  58 |  59 |  60 |  61 |  62 |  63 |
-------------------------------------------------
[7, 6, 15, 23, 14, 5, 4, 13, 22, 31, 39, 30, 21, 12, 3, 2, 11, 20, 29, 38, 
47, 55, 46, 37, 28, 19, 10, 1, 0, 9, 18, 27, 36, 45, 54, 63, 62, 53, 44, 35, 
26, 17, 8, 16, 25, 34, 43, 52, 61, 60, 51, 42, 33, 24, 32, 41, 50, 59, 58, 
49, 40, 48, 57, 56]
And here&#39;s the code.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayWalk {
public static void main(String args[]) {
int height = 8;
int width = 8;
ArrayWalk aw = new ArrayWalk();
int[][] myArray = aw.createArray(height, width);
System.out.println(aw.printArray(myArray));
int[] values = aw.walkArray(myArray);
System.out.println(Arrays.toString(values));
}
private int[][] createArray(int height, int width) {
int[][] myArray = new int[height][width];
int start = 0;
for (int h = 0; h &lt; height; h++) {
for (int w = 0; w &lt; width; w++) {
myArray[h][w] = start;
start++;
}
}
return myArray;
}
private int[] walkArray(int[][] myArray) {
int totalRows = myArray.length;
int totalCols = myArray[0].length;
List&lt;Integer&gt; res = new ArrayList&lt;&gt;(totalRows * totalCols);
List&lt;Integer&gt; diagonal = new ArrayList&lt;&gt;(
Math.max(totalRows, totalCols));
boolean reverseOrder = true;
for (int col = totalCols - 1; col &gt;= 0; col--) {
for (int row = 0; row &lt; totalRows &amp;&amp; col + row &lt; totalCols; row++) {
diagonal.add(myArray[row][col + row]);
}
if (reverseOrder) {
Collections.reverse(diagonal);
}
res.addAll(diagonal);
reverseOrder = !reverseOrder;
diagonal.clear();
}
for (int row = 1; row &lt; totalRows; row++) {
for (int col = 0; col &lt; totalCols &amp;&amp; col + row &lt; totalRows; col++) {
diagonal.add(myArray[col + row][col]);
}
if (reverseOrder) {
Collections.reverse(diagonal);
}
res.addAll(diagonal);
reverseOrder = !reverseOrder;
diagonal.clear();
}
int[] output = new int[res.size()];
for (int i = 0; i &lt; res.size(); i++) {
output[i] = res.get(i);
}
return output;
}
private String printArray(int[][] myArray) {
String output = &quot;&quot;;
for (int h = 0; h &lt; myArray.length; h++) {
output += printDashes(myArray[h].length) + &quot;\n&quot;;
output += printLine(myArray[h]) + &quot;\n&quot;;
}
output += printDashes(myArray[0].length) + &quot;\n&quot;;
return output;
}
private String printDashes(int width) {
int count = width * 6 + 1;
String output = &quot;&quot;;
for (int i = 0; i &lt; count; i++) {
output += &quot;-&quot;;
}
return output;
}
private String printLine(int[] array) {
String output = &quot;|&quot;;
for (int i = 0; i &lt; array.length; i++) {
String value = String.format(&quot;%3d&quot;, array[i]);
output += &quot; &quot; + value + &quot; |&quot;;
}
return output;
}
}
</details>

huangapple
  • 本文由 发表于 2020年8月19日 00:59:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63473322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定